Python类方法重载

时间:2011-11-10 10:06:18

标签: python oop

如何重载类方法? 我失败了:

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'

2 个答案:

答案 0 :(得分: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()

答案 1 :(得分: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