有参及无参装饰器的使用
import time
def delayed_start(func=None, *, duration=1): # 这一层主要是装饰器参数
def decorator(_func): # 这一层主要是将被装饰器装饰的函数传递进来
def wrapper(*args, **kwargs): # 被装饰器装饰的函数的参数传递进来
time.sleep(duration)
return _func(*args, **kwargs) # 真正执行被装饰器装饰的函数
return wrapper
if func is None:
print(func)
return decorator
else:
print("执行了。。。。。。。")
print(func)
return decorator(func)
"""
# 不提供任何参数,使用默认值
@delayed_start
def hello():
pass
1.delayed_start被执行,并将hello当成参数传递给func
2.函数执行到判断func时,因为func有值,所以执行decorator(func)
4.直接返回wrapper
5.执行wrapper()
6.返回_func(),真正函数执行的地方,_func() = hello()
# 拆分调用顺序
def hello():
pass
hello = delayed_start(hello)
# 提供可选的关键字参数
@delayed_start(duration=2)
def hello():
pass
1.delayed_start被执行,因为有关键字参数duration传递,所以func=None
2.函数执行到判断func时,因为func使用了默认值,所以执行decorator
4.并将hello传递给decorator的参数_func,返回wrapper()函数
5.执行wrapper()
6.返回_func(),真正函数执行的地方,_func() = hello()
# 拆分调用顺序
def hello():
pass
hello = delayed_start(duration=2)(hello)
# 提供括号调用,但不提供任何参数
@delayed_start()
def hello():
pass
"""
-------------------------------------------
个性签名:代码过万,键盘敲烂!!!
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!

浙公网安备 33010602011771号