def
outer(x):
def
inner():
# 函式巢狀
return
x
# 跨域訪問,引用了外部變數x
return
inner
# 函式作為返回值
closure
=
outer(
'外部變數'
)
# 函式作為變數賦給closure
print
(closure())
# 執行閉包
實際上,類也可以作為裝飾器。類裝飾器主要依賴於函式__call__()
,每當你呼叫乙個類的示例時,函式__call__()
就會被執行一次。
class count:
def __init__(self,func):
self.func = func
self.count = 0
def __call__(self, *args, **kwargs):
self.count += 1
print('func is called num is:{}'.format(self.count))
return self.func(*args, **kwargs)
@count
def index():
print('i am dyf...')
for i in range(10):
index()
#結果func is called num is:1
i am dyf...
func is called num is:2
i am dyf...
func is called num is:3
i am dyf...
func is called num is:4
i am dyf...
func is called num is:5
i am dyf...
func is called num is:6
i am dyf...
func is called num is:7
i am dyf...
func is called num is:8
i am dyf...
func is called num is:9
i am dyf...
func is called num is:10
i am dyf...
我們定義了類 count,初始化時傳入原函式func()
,而__call__()
函式表示讓變數 num_calls 自增 1,然後列印,並且呼叫原函式。因此,在我們第一次呼叫函式example()
時,num_calls 的值是 1,而在第二次呼叫時,它的值變成了 2 python裝飾器 函式裝飾器,類裝飾器
只要實現此 模式,這個obj就叫乙個裝飾器 參考 函式裝飾器 例子 def decorator func def inner args,kwargs print before.res func args,kwargs print after.return res return inner decor...
python 裝飾器 函式裝飾器 類裝飾器
python函式裝飾器和類裝飾器筆記.usr bin env python coding utf 8 author ivan file decorators.py version from functools import wraps 裝飾器 目的是為了給函式新增附加功能 1.不帶引數裝飾器 此方式...
python類裝飾器詳解 Python裝飾器詳解
python的裝飾器其實是乙個語法糖,第一行是 跟著乙個表示式 第二行必須以def或者class起始 亦即函式或者class的定義 python的裝飾器,必須是可呼叫的物件,而且必須是可以以乙個引數進行呼叫。注意,對返回引數的個數是不做限制的!那麼,python中有幾種可呼叫物件呢?大致有四種 1 ...