Python裝飾器,分兩部分,一是裝飾器本身的定義,一是被裝飾器對(duì)象的定義。
一、函數(shù)式裝飾器:裝飾器本身是一個(gè)函數(shù)。
1.裝飾函數(shù):被裝飾對(duì)象是一個(gè)函數(shù)
[1]裝飾器無參數(shù):
a.被裝飾對(duì)象無參數(shù):
代碼如下:
>>> def test(func):
def _test():
print 'Call the function %s().'%func.func_name
return func()
return _test
>>> @test
def say():return 'hello world'
>>> say()
Call the function say().
'hello world'
>>>
b.被裝飾對(duì)象有參數(shù):
代碼如下:
>>> def test(func):
def _test(*args,**kw):
print 'Call the function %s().'%func.func_name
return func(*args,**kw)
return _test
>>> @test
def left(Str,Len):
#The parameters of _test can be '(Str,Len)' in this case.
return Str[:Len]
>>> left('hello world',5)
Call the function left().
'hello'
>>>
[2]裝飾器有參數(shù):
a.被裝飾對(duì)象無參數(shù):
代碼如下:
>>> def test(printResult=False):
def _test(func):
def __test():
print 'Call the function %s().'%func.func_name
if printResult:
print func()
else:
return func()
return __test
return _test
>>> @test(True)
def say():return 'hello world'
>>> say()
Call the function say().
hello world
>>> @test(False)
def say():return 'hello world'
>>> say()
Call the function say().
'hello world'
>>> @test()
def say():return 'hello world'
>>> say()
Call the function say().
'hello world'
>>> @test
def say():return 'hello world'
>>> say()
Traceback (most recent call last):
File "<pyshell#224>", line 1, in <module>
say()
TypeError: _test() takes exactly 1 argument (0 given)
>>>
由上面這段代碼中的最后兩個(gè)例子可知:當(dāng)裝飾器有參數(shù)時(shí),即使你啟用裝飾器的默認(rèn)參數(shù),不另外傳遞新值進(jìn)去,也必須有一對(duì)括號(hào),否則編譯器會(huì)直接將func傳遞給test(),而不是傳遞給_test()
新聞熱點(diǎn)
疑難解答
圖片精選