为什么用super()调用父类不工作,而使用'直接'调用工作正常吗?Python的继承和超()
class A(object):
def __init__(self, x):
self.x = x
print("Inside A __init__. x = %s" % self.x)
class B(object):
def __init__(self, y):
self.y = y
print("Inside B __init__. y = %s" % self.y)
class C(A,B):
def __init__(self, z):
super(C, self).__init__(6)
super(C, self).__init__(5)
#1. A.__init__(self,6)
#2. B.__init__(self,5)
self.z = z
print("Inside C __init__. z = %s" % self.z)
if __name__ == "__main__":
log = C(2)
随着注释掉 '超级' 我得到的结果是:
Inside A __init__. x = 6
Inside A __init__. x = 5
Inside C __init__. z = 2
所以对 'B' 初始化类的代码不会被调用。但是,使用注释行“#1”和“2号”后的代码工作,因为它应该:
Inside A __init__. x = 6
Inside B __init__. y = 5
Inside C __init__. z = 2
问题:
- 这是什么奇怪的原因“超级()”行为。
- 可以super()在'B'中调用init?
- 是否有任何其他方式调用所有'初始的父类?
它的经典之作:“Raymond Hettinger--超级超级!”,https://www.youtube.com/watch?v=EiOglTERPEo – sobolevn
TL; DR:“超级”不是用于访问特定父类。它的使用必须在所有涉及的类中进行协调。 – chepner
对于那些不喜欢视频的人来说,以下是原始素材:https://rhettinger.wordpress.com/2011/05/26/super-considered-super/ – chepner