python的装饰器模式有点像java的拦截器(AOP)其中分为两种:1.无参数装饰器
deffoo(func):
"""无参数装饰器"""
@functools.wraps(func)
defprocess(*args,**kwargs):
try:
result=func(*args,**kwargs)
returnresult
exceptExceptionasex:
print(ex)
returnprocess
@foo
deftest(val):
print('test %s'%val)
if__name__=='__main__':
test()
"""
相当于不带装饰器
foo(test)(val)
"""
2.带参数的装饰器
deffoo(ext=None):
"""带参数装饰器"""
defprocess(func):
@functools.wraps(func)
definner(*args,**kwargs):
try:
result=func(*args,**kwargs)
print(ext)
returnresult
exceptExceptionasex:
print(ex)
returninner
returnprocess
@foo(ext='ext')
deftest(val):
print('test %s'%val)
if__name__=='__main__':
test('this')
"""
相当于不带装饰器
foo(ext='ext')(test)('this')
"""3.支持带参数和不带参数
deffoo(decorator_=None,ext=None):
"""带参数不带参数均可"""
ifdecorator_andext:
raiseException('args not match')
defprocess(func):
@functools.wraps(func)
definner(*args,**kwargs):
rt=func(*args,**kwargs)
print('ext is %s'%ext)
returnrt
returninner
ifdecorator_:
returnprocess(decorator_)
else:
returnprocess
@foo#相当于foo(test)(val)
@foo(ext='test')#相当于foo(ext='test')(test)(val)
deftest(val):
print('test %s'%val)
return{'status':'done','name':'JIM'}functools.wraps 可以将原函数对象的指定属性复制给包装函数对象, 默认有、、,或者通过参数选择。
>>>fromfunctoolsimportpartial
>>>deffoo(x,y,z):
...print(locals())
...
>>>foo(1,2,3)
{'x':1,'z':3,'y':2}
>>>foo_z=partial(foo,z=5)
>>>foo_z
functools.partial(,z=5)
>>>foo_zisfoo
False
>>>foo_z(10,20)
{'x':10,'z':5,'y':20}
>>>
领取专属 10元无门槛券
私享最新 技术干货