1 user = 'daxin' 2 passwd = '123456' 3 4 def auth_type(auth_type): 5 def auth(func): 6 def auth_page(*args): 7 if auth_type == 'local': 8 username = input('Please input your user:') 9 password = input("Please input your passwd:") 10 if username == user and passwd == password: 11 func(*args) 12 else: 13 print('Username or password Error!') 14 else: 15 print('LDAP') 16 func(*args) 17 return auth_page 18 return auth 19 20 def index(): 21 print('in the index page') 22 @auth_type('local') --> local傳遞到最外層的func 23 def home(): 24 print("in the home page") 25 @auth_type('ldap') 26 def bbs(): 27 print('in the bbs page') 28 29 index() 30 home() 31 bbs()
例子2:app
1 import functools 2 3 def decorator(logintype='3'): 4 def decorator1(func): 5 @functools.wraps(func) 6 def wrapper(*args,**kwargs): 7 if logintype == '1': 8 print('begin call') 9 func(*args,**kwargs) 10 print('end call') 11 elif logintype == '2': 12 print('start call') 13 func(*args,**kwargs) 14 print('over call') 15 else: 16 print('test start') 17 func(*args,**kwargs) 18 print('test start') 19 return wrapper 20 return decorator1 21 22 23 @decorator() 24 def a(name): 25 print('in the F name is %s' % name) 26 27 @decorator('2') 28 def b(): 29 print('in the B') 30 @decorator('1') 31 def c(): 32 print("in the C") 33 34 c() 35 b() 36 a('123')