多重装饰器,即多个装饰器修饰同一个对象【实际上并非完全如此,且看下文详解】
1.装饰器无参数:
代码如下:
>>> def first(func):
print '%s() was post to first()'%func.func_name
def _first(*args,**kw):
print 'Call the function %s() in _first().'%func.func_name
return func(*args,**kw)
return _first
>>> def second(func):
print '%s() was post to second()'%func.func_name
def _second(*args,**kw):
print 'Call the function %s() in _second().'%func.func_name
return func(*args,**kw)
return _second
>>> @first
@second
def test():return 'hello world'
test() was post to second()
_second() was post to first()
>>> test()
Call the function _second() in _first().
Call the function test() in _second().
'hello world'
>>>
实际上它是相当于下面的代码:
代码如下:
>>> def test():
return 'hello world'
>>> test=second(test)
test() was post to second()
>>> test
<function _second at 0x000000000316D3C8>
>>> test=first(test)
_second() was post to first()
>>> test
<function _first at 0x000000000316D358>
>>> test()
Call the function _second() in _first().
Call the function test() in _second().
'hello world'
>>>
2.装饰器有参数:
代码如下:
>>> def first(printResult=False):
def _first(func):
print '%s() was post to _first()'%func.func_name
def __first(*args,**kw):
print 'Call the function %s() in __first().'%/
func.func_name
if printResult:
print func(*args,**kw),'#print in __first().'
else:
return func(*args,**kw)
return __first
return _first
>>> def second(printResult=False):
def _second(func):
print '%s() was post to _second()'%func.func_name
新闻热点
疑难解答