python 20day--装饰器详解

一、装饰器的概念

1、什么 是装饰器:本质就是函数,功能是为其他函数添加新功能

装饰器即函数,装饰即修饰,意指为其他函数添加新功能

2、装饰器需要遵循的原则:

不修改被装饰函数的源代码(开放封闭原则)

为被装饰函数添加新功能后,不修改被修饰函数的调用方式

3、实现装饰器的知识储备:

装饰器=高阶函数+函数嵌套+函数闭包+语法糖

4、装饰器举例:为test()函数加上计算函数运行时间的装饰器,此装饰器为无参装饰器

 1 import time
 2 def timer(func):
 3     def wrapper():
 4         start = time.time()
 5         res = func()
 6         stop = time.time()
 7         print('runtime is %s'%(stop-start))
 8         return func
 9     return wrapper
10 @timer
11 def test():
12     time.sleep(1)
13     print('from test')
14 test()

二、高阶函数

函数的参数是一个函数,返回值是一个函数

三、函数嵌套

函数的内部又定义了一个函数

四、函数闭包

在一个作用域里放入定义变量,相当于打了一个包;相当于往大箱子里面装小箱子

 五、装饰器的应用(语法糖):

@timer 就是装饰器的语法糖,相当于执行了   test = timer(test)

装饰器=高阶函数+函数嵌套+函数闭包+语法糖

带参装饰器举例:为函数加上简单的验证功能:

 1 import time
 2 qujubianliang = {"username":None,"login":False}
 3 def auth_func(func):
 4     def wrapper(*args,**kwargs):
 5         if qujubianliang["username"] and qujubianliang["login"]:
 6             res = func(*args, **kwargs)
 7             return res
 8         username = input("yonghuming").strip()
 9         passwd = input("mima").strip()
10         if username=="sb" and passwd=="123":
11             qujubianliang["username"]=username
12             qujubianliang["login"]=True
13             res = func(*args,**kwargs)
14             print(' i am wrapper')
15             return res
16         else :
17             print('passwd is wrong')
18 
19     return wrapper
20 @auth_func
21 def index():
22     print("welcome to jd")
23 @auth_func
24 def home():
25     print("welcome to home")
26 @auth_func
27 def shopping_car(name):
28     print('%s shopping_car has meimei'%name)
29 index()
30 home()
31 shopping_car('alex')
原文地址:https://www.cnblogs.com/yuzhiboyou/p/10153792.html