python 装饰器传参被装饰的函数带有参数的情况接上一篇,直接上代码import timedef 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 timedef 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 timedef 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)