1.装饰器
定义:给其他函数装饰(添加附加功能)的函数
原则:1.不能修改被装饰的函数的源代码。
2.不能修改北庄施的函数的调用方式
实现所需要求:1.函数即便量
2.高阶函数
3.嵌套函数
高阶函数+嵌套函数=> 装饰器
匿名函数:

1 f = lambda x:x+1 2 print(f(1)) 3 >>>2 4 #匿名函数比起正常函数,不需要指定函数名
嵌套函数:

1 x = 1 2 def a(): 3 x = 2 4 print(x) 5 def b(): 6 x = 3 7 print(x) 8 def c(): 9 x = 4 10 print(x) 11 c() 12 b() 13 a() 14 >>>2 15 3 16 4 17 #嵌套函数调用要一层一层的调用,如果b没有调用那么只会打印"2"
举一个简单的装饰器例子:
学渣版:

1 def timer(func): 2 def deco(*args,**kwargs): #非固定参数传入 3 start_time = time.time() #计算开始时间 4 func(*args,**kwargs) #运行test1 5 stop_time = time.time() #计算结束时间 6 print("运行时间为%s" % (start_time-stop_time)) #"deco"装饰器的作用-计算test1的运行时间 7 return deco 8 @timer #还有一种调用方式,test1=timer(test1),但是这种比较麻烦还是推荐这种,你要装饰哪一个函数就在哪一个函数头部引用 9 def test1(a,b): 10 time.sleep(3) #三秒后运行 11 print("in the test1:%s %s" % (a,b)) 12 test1("123","234") #并没有改变函数的调用方式和源代码 13 >>>in the test1:123 234 14 运行时间为-3.0027999877929688 15 这样应该就明白装饰器的作用了
学霸版:

1 user,passwd = 'zhaoyue','woaini' 2 def auth(func): #这里假装我们有两个页面需要验证,这个函数用来验证 3 def wrapper(*args,**kwargs): 4 username = input("Please your username:") 5 password = input("Please your password") 6 if user == username and passwd == password: 7 print("Hello world!") 8 func(*args,**kwargs) #开始运行传入的函数 9 else: 10 exit("gun") 11 return wrapper #返回结果 12 13 def LOL(): 14 print("in the LOL") 15 @auth 16 def LPL(): 17 print("in the LPL") 18 @auth 19 def LCK(): 20 print("in the LCK") 21 LOL() 22 LPL() 23 LCK() #后面则是"LPL",“LCK”需要验证。
学霸进阶版(这就是学渣和学霸的区别,一道题学渣考虑的是能不能做出来,而学霸考虑的是用几种方法做出来!!!)

1 user,passwd = 'zhaoyue','woaini' 2 def auth(auth_type): 3 print("