gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 10:03:38 27 4
gpt4 key购买 nike

这是怎么回事。我已经查看了有关堆栈溢出的其他解决方案,但从我所看到的来看似乎都没有用。我有一个基础对象,它有一个改 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com