在子类 Python 中调用基类方法



这是怎么回事。我已经查看了堆栈溢出的其他解决方案,但从我所看到的来看似乎不起作用。我有一个基对象,它有一个更改基属性值的方法。当我在子类(继承(中调用基函数时,我得到子类没有属性"baseAttribute">

class GameObject(object):
 #This is the base class for gameObjects
 def __init__(self):
     self.components = {}
 def addComponent(self, comp):
     self.components[0] = comp #ignore the index. Placed 0 just for illustration
class Circle(GameObject):
 #circle game object 
 def __init__(self):
     super(GameObject,self).__init__()
     #PROBLEM STATEMENT
     self.addComponent(AComponentObject())
     #or super(GameObject,self).addComponent(self,AComponentObject())
     #or GameObject.addComponent(self, AComponentObject())

编辑:抱歉,我最初从未通过自我。

简单 - 省略第二个自我:

self.addComponent(AComponentObject())

你看,上面实际上翻译为

addComponent(self, AComponentObject())

换句话说:本质上,"OO"适用于具有隐式this/self指针(无论您如何命名(作为参数的函数。

您对.addComponent()方法使用了不正确的参数。

# ...
class Circle(GameObject):
 def __init__(self):
     super(GameObject,self).__init__()
     # NOT A PROBLEM STATEMENT ANYMORE
     self.addComponent(AComponentObject())
     # ...

最新更新