
>>> def check_permission(func):
def wrapper(*args,**kwargs):
if kwargs.get('username')!='admin':
raise Exception('Sorry.You are not allowed.')
return func(*args,**kwargs)
return wrapper
>>> class ReadWriteFile(object):
'''The check_permisson function is used as a decorator'''
@check_permission
def read(self,username,filename):
return open(filename,'r').read()
def write(self,username,filename,content):
open(filename,'a+').write(content)
write=check_permission(write)
>>> t=ReadWriteFile()
>>> print('Originally...')
Originally...
>>> print(t.read(username='admin',filename='/Users/c2apple/Desktop/file.txt'))
hellow world my birthday
>>> print('Now,try to write to a file...')
Now,try to write to a file...
>>> t.write(username='admin',filename='/Users/c2apple/Desktop/file.txt',content='\nhello my love is ended')
>>> print('After calling to write....')
After calling to write....
>>> print(t.read(username='admin',filename='/Users/c2apple/Desktop/file.txt'))
hellow world my birthday
hello my love is ended