1. 装饰器
- 装饰器本身就是函数,功能是为其他函数添加附加功能
- 装饰器的设计原则:
(a). 不修改被修饰函数的源代码;
(b). 不修改被修改函数的调用方法。
- 装饰器=高阶函数+函数嵌套+闭包
- 装饰器框架
1 def timmer(func): 2 def wrapper(): 3 func() 4 return wrapper 5 func = timmer() 6 func()
2. 装饰器实例1:计算被修饰函数的运行时间
1 import time 2 def bin(name,age): 3 time.sleep(3) 4 print("I am %s, I am %s years old" %(name,age)) 5 time.sleep(3) 6 def timer(func): 7 def wrapper(*args,**kwargs): 8 star = time.time() 9 func(*args,**kwargs) 10 stop = time.time() 11 res = stop-star 12 return res 13 return wrapper 14 bin = timer(bin) #相当于wrapper = timer(bin) 15 dif_time = bin("alex",18) #相当于dif_time = wrapper("alex",18) 16 print("被修饰函数的运行时间为%s" %dif_time) 17 18 """ 19 运行结果: 20 I am alex, I am 18 years old 21 被修饰函数的运行时间为6.001323223114014 22 """
3. 装饰器实例2:登录界面添加身份认证功能
1 user_list = [{"name":"stephen","passwd":"123"}, 2 {"name": "klay", "passwd": "123"}, 3 {"name": "durant", "passwd": "123"}, 4 {"name": "green", "passwd": "123"}] 5 def home(name): 6 print("Welcome %s to enter the system" %name) 7 def certification(func): 8 def wrapper(name): 9 passwd = input("please enter your password:").strip() 10 for item in user_list: 11 if item["name"]==name and item["passwd"]==passwd: 12 func(name) 13 return 1 14 return 0 15 return wrapper 16 home = certification(home) #相当于wrapper = certification(home) 17 res = home("klay") #相当于wrapper("klay") 18 if not res: 19 print("密码或用户名输入错误") 20 21 """ 22 运行结果: 23 please enter your password:123 24 Welcome klay to enter the system 25 """