python 装饰器 part2
python 装饰器
传参
被装饰的函数带有参数的情况接上一篇,直接上代码
import time def decorator(func): def process(*args, **kwargs): start = time.time() func(*args, **kwargs) end = time.time() print('函数func(也就是被装饰的函数)的运行时间是:{}'.format(end-start)) return process @decorator # python 装饰器的正确使用,不需要传参 def decorated(): time.sleep() print('decorated function') @decorator # python 装饰器的正确使用,需要传参 def decorated(key, val): time.sleep() print('decorated function') # 此时不用再像上面一样赋值,可以直接调用 decorated() decorated(key, val)
</python>
返回值
被装饰的函数有返回值在装饰器内部需return被装饰函数的调用代码:
import time def decorator(func): def process(*args, **kwargs): start = time.time() return func(*args, **kwargs) # end = time.time() # print('函数func(也就是被装饰的函数)的运行时间是:{}'.format(end-start)) return process @decorator # python 装饰器的正确使用,不需要传参 def decorated(): time.sleep() print('decorated function') return '来自不带参数的被装饰函数' @decorator # python 装饰器的正确使用,需要传参 def decorated(key, val): time.sleep() print('decorated function') return '来自带有参数的被装饰函数' # 此时不用再像上面一样赋值,可以直接调用 decorated() decorated(key, val)
装饰器带参数
@decorator(val='')需要对装饰期代码再包装一层
代码
import time def warpper(val_type): def decorator(func): def process(*args, **kwargs): start = time.time() return func(*args, **kwargs) return process return decorator @decorator(val_type='') # python 装饰器的正确使用,不需要传参 def decorated(): time.sleep() print('decorated function') return '来自不带参数的被装饰函数' @decorator(val_type='') # python 装饰器的正确使用,需要传参 def decorated(key, val): time.sleep() print('decorated function') return '来自带有参数的被装饰函数' # 此时不用再像上面一样赋值,可以直接调用 decorated() decorated(key, val)
相关推荐
夜斗不是神 2020-11-17
huavhuahua 2020-11-20
Yasin 2020-11-16
xiaoseyihe 2020-11-16
千锋 2020-11-15
diyanpython 2020-11-12
chunjiekid 2020-11-10
wordmhg 2020-11-06
YENCSDN 2020-11-17
lsjweiyi 2020-11-17
houmenghu 2020-11-17
Erick 2020-11-17
HeyShHeyou 2020-11-17
以梦为马不负韶华 2020-10-20
lhtzbj 2020-11-17
pythonjw 2020-11-17
dingwun 2020-11-16
lhxxhl 2020-11-16