python - 在子类python中调用基类方法

标签 python python-2.7 oop inheritance

这是怎么回事。我已经查看了有关堆栈溢出的其他解决方案,但从我所看到的来看似乎都没有用。我有一个基础对象,它有一个改 rebase 础属性值的方法。当我在子类(继承)中调用基函数时,我得到子类没有属性“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 。

最佳答案

简单——去掉第二个自己:

self.addComponent(AComponentObject())

你看,上面其实转化为

addComponent(self, AComponentObject())

换句话说:本质上“面向对象”适用于具有隐式 this/self 指针的函数(无论您如何命名)作为论据。

关于python - 在子类python中调用基类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42098354/

相关文章:

python - 如何加入元组日期时间

C++ 多态性 : from parent class to child

java - 我如何限制使用它们的子类的抽象类中的方法参数?

python - 访问使用 ElementTree 解析的 xml 文件中的嵌套子项

Python Zeep - HTTP 状态 415(无可用内容)

python-2.7 - 更新 for 循环中的 range() 函数

python - 您可以使用 Python 正则表达式从偏移量向后搜索吗?

java - 如何更改或使用创建对象的类中的变量?

python - Python 3.6 sum() 是否有 `start=0` 关键字参数?

python - 获取 APSW 中的所有内容