2016-09-27 29 views
-1

我想了解一個類的方法定義其內容類似於以下:意義Python中的「@package」裝飾

@package(type='accounts', source='system') 
def get(self, [other arguments]): 
    [function body] 

什麼是@package裝飾的意義?我無法找到關於此的文檔。

回答

3

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()是一個裝飾工廠,生產實際的裝飾。

+0

有趣的使用裝飾工廠+1 –