【问题标题】:Get variable from parent class for use in method of child class [duplicate]从父类获取变量以用于子类的方法[重复]
【发布时间】:2015-11-29 01:07:27
【问题描述】:

我试图了解 Python 中的父类和子类是如何工作的,但遇到了这个看似简单的问题:

class parent(object):

    def __init__(self):
        self.data = 42


class child(parent):

    def __init__(self):
        self.string = 'is the answer!'

    def printDataAndString(self):
        print( str(self.data) + ' ' + self.string )


c = child()
c.printDataAndString()

我期待字符串 42 是答案! 但我明白了

AttributeError: 'child' 对象没有属性 'data'

我错过了什么?

我对@9​​87654322@ 和super(parent,...) 进行了实验,但无法做到正确。

【问题讨论】:

  • FWIW,您可以使用parent.__init__(self) 调用父级__init__,但首选使用super,因为它可以正确处理多重继承。

标签: python inheritance


【解决方案1】:

由于你的child有自己的__init__()函数,你需要调用父类'__init__(),否则它不会被调用。示例 -

def __init__(self):
    super(child,self).__init__()
    self.string = 'is the answer!'

super() from documentation-

super(type[, object-or-type])

返回一个代理对象,该对象将方法调用委托给该类型的父类或同级类。这对于访问已在类中重写的继承方法很有用。搜索顺序与 getattr() 使用的相同,只是跳过了类型本身。

所以super()的第一个参数应该是子类(你要调用的'父类'方法),第二个参数应该是对象本身,即self。因此,super(child, self)

Python 3.x 中,您可以简单地调用 -

super().__init__()

它会从正确的父类调用__init__() 方法。

【讨论】:

  • 如果我的父类的_init_ 函数包含大量变量声明和一些重量级文件io - 有没有办法只获取特定变量?否则每次我创建子类的实例时,它都会调用我父类的_init_ 函数,如果我只需要那一两个变量,我想这有点矫枉过正?
  • 难道不能在子类本身中定义那一两个变量,而不是调用super().__init__()
  • @thewaywewalk:简单的答案就是 Anand 所说的:只需在子级的 __init__ 方法中声明这些变量,不要调用父级的 __init__ 方法。但是,如果孩子不需要所有额外的东西,那么您应该考虑重新组织继承并交换父母和孩子的角色。父类应该是基类,子类有花哨的附加功能。
猜你喜欢
  • 2020-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-28
  • 1970-01-01
  • 2013-08-21
相关资源
最近更新 更多