装饰器
定义:本质是函数,为其他函数添加附加的功能。
原则:1、不能修改原函数的源代码
2、不能修改被原函数的调用方式
重点理解:
1、函数即“变量”
2、高阶函数:返回值中包含函数名
3、嵌套函数
高阶函数 + 嵌套函数 = 装饰器
热身: 先感受一下Python的解释器,结果可能和你预想的不同
__author__ = 'jcx' def foo(): print("in the foo") bar() #解释器依次解释,先声明print后bar def bar(): print("in the bar") #找到bar,定义 foo() #只要在调用前声明就可以
1 Output: 2 in the foo 3 in the bar
应用:
1、通用版 打印程序执行时间
1 __author__ = 'jcx' 2 3 import time 4 5 def timer(func): #timer(test1) func = test1 6 def deco(*args, **kwargs): #这样写,就可以使被装饰的函数可以带参数 7 start_time = time.time() 8 func(*args, **kwargs) 9 stop_time = time.time() 10 print("Func RunTime = %s" % (stop_time - start_time)) 11 return deco 12 13 @timer #等于作了这部赋值 test1 = timer(test1) 14 def test1(): 15 time.sleep(0.1) 16 print("in the test1") 17 18 @timer 19 def test2(name,age): #test2 = timer(test2) test2() = deco() 20 print("test2:", name,age) 21 22 test1() #实际是在执行deco() 23 test2("jcx",24) #带参数
24
输出结果:
1 in the test1 2 Func RunTime = 0.10228705406188965 3 test2: jcx 24 4 Func RunTime = 2.09808349609375e-05
2、多种方式登录网页/语法糖/嵌套
1 __author__ = 'jcx' 2 3 4 import time 5 user,passwd = 'jcx', 'jcx123' 6 7 def auth(auth_type): 8 print("auth type: ", auth_type) 9 def outer_wrapper(func): 10 def wrapper(*args, **kwargs): 11 # print("wrapper func: ", *args,**kwargs) 12 if auth_type == "local": 13 username = input("Username:".strip()) 14 password = input("Password:".strip()) 15 if user == username and passwd == password: 16 print("