装饰器
装饰器=高阶函数+嵌套函数
在嵌套函数timer()内定义一个高阶函数deco()
用高阶函数deco()装饰函数test1()
同时返回高阶函数名——函数内存地址deco
然后test1=deco
#把deco内存地址传给test1变量
此时执行test1()就是执行deco()即 test1()=deco()
如果原来的test1()有参数,
则高阶函数也应该接收参数test1(a)=deco(a)
新test1()比旧test1()功能更全,
#无参数传递函数的装饰举例
import time
def timer(func): #装饰器函数---嵌套函数
def deco(): #定义实际装饰函数----高阶函数
#print(func)
start_time=time.time()
func() #被装饰函数
stop_time=time.time()
print("程序运行时间为:%s" %(start_time-stop_time))
return deco #返回高阶函数的内存地址(函数名字)
@timer #装饰器的使用
def test1():
time.sleep(3)
print("in test1")
# def test2():
# time.sleep(4)
# print("in test2")
test1() #本质是deco()?
#有参数传递装饰器
import time
def timer(func):
def deco(*args,**kwargs):
#print(func)
start_time=time.time()
func(*args,**kwargs)
stop_time=time.time()
print("程序运行时间为:%s" %(start_time-stop_time))
return deco
@timer
def test1():
time.sleep(3)
print("in test1")
@timer
def test2(name):
time.sleep(1)
print(name)
test1()
test2("wanghui")
-
- 装饰器的高级用法
import time
user,passwd = 'alex','abc123'
def auth(auth_type):
print("auth func:",auth_type)
def outer_wrapper(func):
def wrapper(*args, **kwargs):
print("wrapper func args:", *args, **kwargs)
if auth_type == "local":
username = input("Username:").strip()
password = input("Password:").strip()
if user == username and passwd == password:
print("\033[32;1mUser has passed authentication\033[0m")
res = func(*args, **kwargs) # from home
print("---after authenticaion ")
return res
else:
exit("\033[31;1mInvalid username or password\033[0m")
elif auth_type == "ldap":
print("搞毛线ldap,不会。。。。")
return wrapper
return outer_wrapper
def index():
print("welcome to index page")
@auth(auth_type="local") # home = wrapper()
def home():
print("welcome to home page")
return "from home"
@auth(auth_type="ldap")
def bbs():
print("welcome to bbs page")
index()
print(home()) #wrapper()
bbs()
三层意思
第一层,装饰器添加验证功能
第二层,装饰器添加返回功能
第三层,根据装饰器函数的关键字参数,选择验证方式
验证方式可以在装饰器的高阶函数里面实现
但关键字参数传递给装饰器需要再加一层嵌套函数接收-关键字参数