-1
我想了解一個類的方法定義其內容類似於以下:意義Python中的「@package」裝飾
@package(type='accounts', source='system')
def get(self, [other arguments]):
[function body]
什麼是@package
裝飾的意義?我無法找到關於此的文檔。
我想了解一個類的方法定義其內容類似於以下:意義Python中的「@package」裝飾
@package(type='accounts', source='system')
def get(self, [other arguments]):
[function body]
什麼是@package
裝飾的意義?我無法找到關於此的文檔。
Python標準庫中沒有默認的package
修飾符。
裝飾者只是一個簡單的表達;將會有一個package()
在同一個模塊中調用(或者定義爲一個函數或類,或者從另一個模塊導入)。
行@package(type='accounts', source='system')
執行表達式package(type='accounts', source='system')
,並且返回值用於修飾get()
函數。您可以將其讀取爲:
def get(self, [other arguments]):
[function body]
get = package(type='accounts', source='system')(get)
除名稱get
只設置一次。
例如,package
可以定義爲:
def package(type='foo', source='bar'):
def decorator(func):
def wrapper(*args, **kwargs):
# do something with type and source
return func(*args, **kwargs)
return wrapper
return decorator
所以package()
decorator()
返回,這反過來又返回wrapper()
; package()
是一個裝飾工廠,生產實際的裝飾。
有趣的使用裝飾工廠+1 –