1 >>> def check_permission(func):
 2 def wrapper(*args,**kwargs):
 3 if kwargs.get('username')!='admin':
 4 raise Exception('Sorry.You are not allowed.')
 5 return func(*args,**kwargs)
 6 return wrapper
 7 
 8 >>> class ReadWriteFile(object):
 9 '''The check_permisson function is used as a decorator'''
10 @check_permission
11 def read(self,username,filename):
12 return open(filename,'r').read()
13 def write(self,username,filename,content):
14 open(filename,'a+').write(content)
15 write=check_permission(write)
16 
17 
18 >>> t=ReadWriteFile()
19 >>> print('Originally...')
20 Originally...
21 >>> print(t.read(username='admin',filename='/Users/c2apple/Desktop/file.txt'))
22 hellow world my birthday
23 >>> print('Now,try to write to a file...')
24 Now,try to write to a file...
25 >>> t.write(username='admin',filename='/Users/c2apple/Desktop/file.txt',content='\nhello my love is ended')
26 >>> print('After calling to write....')
27 After calling to write....
28 >>> print(t.read(username='admin',filename='/Users/c2apple/Desktop/file.txt'))
29 hellow world my birthday
30 hello my love is ended

 

相关文章:

  • 2021-09-13
  • 2022-12-23
  • 2022-12-23
  • 2022-02-01
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-11
猜你喜欢
  • 2021-08-22
  • 2021-10-11
  • 2021-11-09
  • 2022-01-03
  • 2021-06-29
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案