Get variable from parent class for use in method of child class
本问题已经有最佳答案,请猛点这里访问。
我试图理解Python中的父类和子类是如何工作的,我遇到了这个看似简单的问题:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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' object has no attribute 'data'
我错过了什么?
我用
由于您的
1 2 3 | def __init__(self): super(child,self).__init__() self.string = 'is the answer!' |
文件中的
super(type[, object-or-type])
Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class. The search order is same as that used by getattr() except that the type itself is skipped.
因此,
在python 3.x中,您可以简单地调用-
1 | super().__init__() |
它将从正确的父类调用