在子类python中调用基类方法

2024-09-28 01:34:50 发布

您现在位置: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())

编辑: 抱歉,我从来没有过自我。在


Tags: theselffor属性objectinitdefcomponents
2条回答

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

# ...

class Circle(GameObject):

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

简单-忽略第二个自我:

self.addComponent(AComponentObject())

你看,上面的内容实际上是

^{pr2}$

换言之:本质上,“OO”的作用是使用一个隐式this/self指针作为参数的函数。在

相关问题 更多 >

    热门问题