沒有參數的裝飾器會直接接受原函數作爲參數,定義如下:
def deco(func):
if func.__doc__ == None:
print func,'has no __doc__,its a bad habit.'
else:
print func,':',func.__doc__,'.'
return func
#在這時已經開始運行裝飾器
@deco
def func1():
'I have a __doc__'
print 'func1 is running'
@deco
def func2():
print 'func2 is running'
func1()
func2()
###########輸出結果:###########
<function func1 at 0x0000000002ACD9E8> : I have a __doc__ .
<function func2 at 0x0000000002AD3048> has no __doc__,its a bad habit.
func1 is running
func2 is running
def outerdeco(args):
def innerdeco(func):
print func,args
return func
return innerdeco
@outerdeco('outerdeco-args')
def func3():
print 'func3 is running'
func3()
############輸出結果:###########
<function func3 at 0x0000000002B61198> outerdeco-args
func3 is running
def outerdeco4(args):
def innerdeco4(func):
def funcdeco(a,b):
print func,args
ret = func(a,b)
return ret
return funcdeco
return innerdeco4
@outerdeco4('Add two numbers.')
def func4(a,b):
print 'The answer is :',a + b
return a + b
func4(3,5)
########輸出結果:#######
<function func4 at 0x0000000002C92278> Add two numbers.
The answer is : 8
它的作用就是在函數調用方法不變的情況下,把此函數包裝成另一個函數來使用 。