多重裝飾器,即多個裝飾器修飾同一個對象【實際上并非完全如此,且看下文詳解】
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
新聞熱點
疑難解答