如何重载类方法? 我失败了:
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'
答案 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