【发布时间】:2012-09-27 17:11:22
【问题描述】:
我有两个班级,Field 和 Background。它们看起来有点像这样:
class Field( object ):
def __init__( self, a, b ):
self.a = a
self.b = b
self.field = self.buildField()
def buildField( self ):
field = [0,0,0]
return field
class Background( Field ):
def __init__( self, a, b, c ):
super(Background, self).__init__( a, b )
self.field = self.buildField( c )
def buildField( self, c ):
field = [c]
return field
a, b, c = 0, 1, 2
background = Background( a, b, c )
这个错误指向Field的buildField():
"TypeError: buildField() takes exactly 2 arguments (1 given)."
我希望首先调用 Background init()。要将 "a, b" 传递给 Fields init(),Field 分配 a 和 b,然后将其中包含三个 0 的列表分配给 field。然后让 Background 的 init() 继续,然后调用它自己的 buildField() 并用包含 c 的列表覆盖 self.field。
似乎我并不完全理解 super(),但是在查看了网络上和此处的类似继承问题后,我无法找到解决问题的方法。
我期望像 c++ 这样一个类可以覆盖继承的方法的行为。我怎样才能做到这一点或类似的东西。
我发现与此相关的大多数问题都是使用双下划线的人。我对 super 继承的经验是使用继承的类 init() 将不同的变量传递给超类。不涉及覆盖任何内容。
【问题讨论】:
标签: python inheritance methods super overwrite