the*_*alk 4 python inheritance
我试图理解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()
Run Code Online (Sandbox Code Playgroud)
我期待字符串42就是答案!但我明白了
AttributeError:'child'对象没有属性'data'
我错过了什么?
我experimentated与pass和也super(parent,...),但不能得到它的权利.
由于你child有自己的__init__()函数,你需要调用父类' __init__() ,否则它不会被调用.示例 -
def __init__(self):
super(child,self).__init__()
self.string = 'is the answer!'
Run Code Online (Sandbox Code Playgroud)
super(类型[,object-or-type])
返回将方法调用委托给父类或兄弟类类型的代理对象.这对于访问已在类中重写的继承方法很有用.搜索顺序与getattr()使用的搜索顺序相同,只是跳过了类型本身.
所以第一个参数super()应该是子类(你要调用它的'父类'方法),第二个参数应该是对象本身,即self.因此,super(child, self).
在Python 3.x中,您只需调用 -
super().__init__()
Run Code Online (Sandbox Code Playgroud)
它会__init__()从正确的父类调用该方法.