2017-01-26 89 views
1

基於類的裝飾屬性可以說我有一類爲基礎的裝飾,像這樣的說法:訪問以參數

class Decorator: 
    def __init__(self, arg): 
     self.arg = arg 

    def __call__(self, func): 
     def wrap(): 
      # something with self.arg 
      func() 
     return wrap 

當我有一個裝飾功能foo,我能做到以下幾點:

deco = Decorator("ARG") 
def foo(): 
    pass 
foo = deco(foo) 
deco.arg = "CHANGE ARG" 

以某種方式訪問​​/更改deco.arg如果我使用@ -Syntax?

@Decorator("ARG") 
def foo(): 
    pass 

# How to change/access the arg-attribute? 

回答

1

您可以創建一個封閉:

def Decorator(arg): 
    class InnerDecorator: 
     def __init__(self, func): 
      self.func = func 
      # make arg an instance attribute 
      self.arg = arg 

     def __call__(self): 
      return self.func() 

    return InnerDecorator 

@Decorator("ARG") 
def foo(): 
    pass 

然後設置的功能的屬性:

>>> foo.arg 
'ARG' 
>>> foo.arg = 'WOW' 
>>> foo.arg 
'WOW' 
+0

@Robert_Jordan沒有問題:) – MSeifert