【发布时间】: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'
我错过了什么?
我对@987654322@ 和super(parent,...) 进行了实验,但无法做到正确。
【问题讨论】:
-
FWIW,您可以使用
parent.__init__(self)调用父级__init__,但首选使用super,因为它可以正确处理多重继承。
标签: python inheritance