python3.x 浅谈修饰器
#装饰器用法,好处
#简化代码,避免重复性代码
#打印日志 @log
#检测性能 @performance
#数据库事务 @transaction
#URL路由 @post('/register')
简单例子:
@new_addlog
def function(x):
return x*2
等价于===>>
def function(x):
return x*2
function=new_addlog(function)
#修饰器用法1
'''
def reducedata(x):
return x*2
def addlog(f):
def newFunction(data):
print('call: '+f.__name__+'()...',data)
return (f(data))
return newFunction
reducedata = addlog(reducedata)
print(reducedata(5))
'''
#修饰器用法2 tips:先定义修饰器,在使用@绑定
def addLOG(f):#指针地址不能带参
def log(x,y):
print('call: '+f.__name__)
return f(x,y)
return log
@addLOG #需要先定义
def add(x,y):
return x+y
print(add(5,6))
#按照道理应该cpp也能这么做,但逻辑太复杂,py风格比较好理解,
#将需要扩展的api封装起来,增加需要的功能,完成之后,在执行封装的api,就这么简单
扩展functools.wraps(),先看下原型api
>>> from functools import wraps
>>> def my_decorator(f):
... @wraps(f)
... def wrapper(*args, **kwds):
... print('Calling decorated function')
... return f(*args, **kwds)
... return wrapper
...
>>> @my_decorator
... def example():
... """Docstring"""
... print('Called example function')
...
>>> example()
Calling decorated function
Called example function
>>> example.__name__
'example'
>>> example.__doc__
'Docstring'
wraps把原函数所有必要的属性复制到新函数上,与原来简单的装饰器相比不只是增加了新功能,还
保留原函数的属性。