python装饰器不改变原函数属性,带参装饰器
2021-03-29 00:25
import datetime,time
def copy_properties(src):
def wrapper(dst):
dst.__name__=src.__name__
dst.__doc__=src.__doc__
dst.__qualname__=src.__qualname__
return dst
return wrapper
def logger(fn):
#logger中不能直接引用copy_properties中的嵌套函数,利用copy_properties的返回值进行引用,fn实参形成闭包,等价于copy_properteis.wrapper(有闭包)
# => logger.wrapper = copy_properties.wrapper(logger.wrapper)
@copy_properties(fn)
def wrapper(*args,**kwargs):
‘this is the wrapper‘
print("args={},kwargs={}".format(args,kwargs))
start=datetime.datetime.now()
ret=fn(*args,**kwargs)
duration=datetime.datetime.now()-start
print(‘function {} took {}s‘.format(fn.__name__,duration.total_seconds()))
return ret
return wrapper
@logger
def add(x,y):
‘this is the function‘
print(‘call add‘)
time.sleep(2)
return x+y
add(5,7)
上一篇:C语言字符串总结
文章标题:python装饰器不改变原函数属性,带参装饰器
文章链接:http://soscw.com/index.php/essay/69273.html