2011-11-10 66 views
1

如何重載類方法? 我失敗:Python類方法重載

class D(object): 
    def create(self): 
     foo = 100 
     bar = 'squirrels' 
     baz = 'I have %d insane %s in my head.' % (foo, bar) 
     return baz  

class C(D): 
    def create(self): 
     super(C, self).create() 
     baz = 'I have %s cute %s in my yard.' % (self.foo, self.bar) 

C().create() 

回溯是:

AttributeError: 'C' object has no attribute 'foo' 

回答

3

您已嘗試將局部變量用作類屬性。嘗試執行以下更改:

class D(object): 
    def create(self): 
     self.foo = 100 
     self.bar = 'squirrels' 
     baz = 'I have %d insane %s in my head.' % (self.foo, self.bar) 
     return baz 

class C(D): 
    def create(self): 
     super(C, self).create() 
     print self.foo 
     self.baz = 'I have %s cute %s in my yard.' % (self.foo, self.bar) 

C().create() 
0

D.create你不設置self,這意味着變量foo是函數的局部變量的變量。

class D(object): 
    def create(self): 
     self.foo = 100 
     self.bar = 'squirrels' 
     self.baz = 'I have %d insane %s in my head.' % (self.foo, self.bar) 
     return self.baz 
+0

'create()'不返回'D'和' 'C'對象,但是一個字符串。所以'__init__'可能不會導致某處... – glglgl

+0

@glglgl你是對的,回答編輯。 –