【问题标题】:calling a base class method in the child class python在子类python中调用基类方法
【发布时间】:2017-02-07 19:31:10
【问题描述】:

发生了什么事。我已经查看了有关堆栈溢出的其他解决方案,但从我所看到的情况来看似乎没有。我有一个带有更改基本属性值的方法的基本对象。当我在子类(继承)中调用基函数时,我发现子类没有属性“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())

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

【问题讨论】:

    标签: python python-2.7 oop inheritance


    【解决方案1】:

    简单——省略第二个自我:

    self.addComponent(AComponentObject())
    

    你看,上面实际上翻译成

    addComponent(self, AComponentObject())
    

    换句话说:本质上“OO”适用于具有 implicit this/self 指针的函数(无论你如何命名)作为论据。

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2012-05-11
        • 2010-11-19
        • 1970-01-01
        • 2021-05-13
        • 2012-06-28
        • 2013-03-23
        • 1970-01-01
        • 2011-01-05
        • 2016-10-05
        相关资源
        最近更新 更多