2010-06-08 119 views
15

幫助一個人。似乎無法得到裝飾工作與繼承。將其分解成我的臨時工作區中最簡單的示例。仍似乎無法得到它的工作。Python裝飾器和繼承

class bar(object): 
    def __init__(self): 
     self.val = 4 
    def setVal(self,x): 
     self.val = x 
    def decor(self, func): 
     def increment(self, x): 
      return func(self, x) + self.val 
     return increment 

class foo(bar): 
    def __init__(self): 
     bar.__init__(self) 
    @decor 
    def add(self, x): 
     return x 

糟糕,名稱「裝飾」未定義。

好的,@bar.decor怎麼樣? TypeError:必須用bar實例作爲第一個參數調用unbound方法「decor」(取而代之的是函數實例)

好的,@self.decor怎麼樣?名稱「自我」未定義。

好的,@foo.decor怎麼樣?!名稱「foo」未定義。

AaaaAAaAaaaarrrrgggg ...我做錯了什麼?

+0

在你的榜樣,你可以有'返回X + self.val'在'foo'的add'的'定義。你能不能在你的實際代碼中做到這一點? – 2010-06-08 20:52:16

+0

這是一個精煉的示例代碼,突出顯示了我正面臨的問題。如果代碼很簡單,那麼是的。但是,事實並非如此。 – wheaties 2010-06-08 21:04:10

回答

19

定義decor作爲一個靜態方法和使用形式@bar.decor

class bar(object): 
    def __init__(self): 
     self.val = 4 
    def setVal(self,x): 
     self.val = x 
    @staticmethod 
    def decor(func): 
     def increment(self, x): 
      return func(self, x) + self.val 
     return increment 

class foo(bar): 
    def __init__(self): 
     bar.__init__(self) 
    @bar.decor 
    def add(self, x): 
     return x 
+0

這可以更好地發揮作用,因爲在兩個函數定義中都不使用'self'。 – exupero 2010-06-08 21:00:03

+1

@eshull:實際上,'decor'可以是一個靜態方法,儘管有'self'引用。 'self'只在'increment()'內被引用,並且在'foo'實例上調用'f.add(10)'時,'increment()'中的'self'參數會引用'f',增量將按預期工作。 – 2010-06-08 21:07:36

+0

這看起來像它會工作。要離開工作,但如果是這樣,我將以此爲答案。謝謝! – wheaties 2010-06-08 21:23:23