Python装饰器
1. 定义
本质是函数,用来装饰其他函数,为其他函数添加附加功能
2. 原则
a. 不能修改被装饰函数的源代码
b. 不能修改被装饰的函数的调用方式
3. 实现装饰器知识储备
a. 函数就是变量
b. 高阶函数
i. 把一个函数当作实参传给另外一个函数,在不修改被装饰函数源代码情况下为其添加功能
ii. 返回值中包含函数名, 不修改函数的调用方式
c. 嵌套函数
高阶函数+嵌套函数==》装饰器

1 # Author: Lockegogo 2 3 user, passwd = 'LK', '130914' 4 def auth(auth_type): 5 print('auth func:', auth_type) 6 def outher_wrapper(func): 7 def wrapper(*args, **kwargs): 8 print('wrapper func:', *args, **kwargs) 9 if auth_type == 'local': 10 username = input('username:').strip() 11 password = input('password:').strip() 12 if user == username and password == passwd: 13 print('\033[32;1mUser has passed authentication\033[0m') 14 res = func(*args, **kwargs) 15 return res 16 else: 17 exit('\033[32;1mInvalid Username or password\033[0m') 18 elif auth_type == 'ldap': 19 print('ldap,不会') 20 return wrapper 21 return outher_wrapper 22 23 def index(): 24 print('welcome to index page') 25 @auth(auth_type='local') # home = outher_wrapper(home) 26 def home(): 27 print('welcome to home page') 28 return 'from home' 29 @auth(auth_type='ldap') 30 def bbs(): 31 print('welcome to bbs page') 32 33 index() 34 print(home()) 35 bbs()