【发布时间】:2013-06-20 14:14:45
【问题描述】:
我一直试图了解super() 在多重继承上下文中的行为。我很困惑为什么在 test2.py 的父类中对 super() 的调用会导致父母双方都调用 __init__()?
test1.py
#!/usr/bin/env python
class A(object):
def __init__(self):
self.A = "A"
print self.A
class B(object):
def __init__(self):
self.B = "B"
print self.B
class C(A, B):
def __init__(self):
self.C = "C"
print self.C
super(C, self).__init__()
if __name__ == '__main__':
print "Without super() in parent __init__():"
c = C()
print c.__dict__
print C.__mro__
产生:
$ ./test.py
Without super() in parent __init__():
C
A
{'A': 'A', 'C': 'C'}
(<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <type 'object'>)
test2.py
#!/usr/bin/env python
class A(object):
def __init__(self):
self.A = "A"
print self.A
super(A, self).__init__()
class B(object):
def __init__(self):
self.B = "B"
print self.B
super(B, self).__init__()
class C(A, B):
def __init__(self):
self.C = "C"
print self.C
super(C, self).__init__()
if __name__ == '__main__':
print "With super() in parent __init__():"
c = C()
print c.__dict__
print C.__mro__
产生:
$ ./test2.py
With super() in parent __init__():
C
A
B
{'A': 'A', 'C': 'C', 'B': 'B'}
(<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <type 'object'>)
【问题讨论】:
-
" 我很困惑为什么在 test2.py 的父类中对 super() 的调用会导致父类都调用 __init__()? - 因为这就是
super()的重点:确保以正确的顺序调用层次结构中的所有类。 -
@LennartRegebro 我现在意识到这一点,因为我已经阅读了@BrenBarn 的答案和这篇文章rhettinger.wordpress.com/2011/05/26/super-considered-super 我很困惑,因为我认为
super()会无条件地调用父类(在A和B的情况是object)。令我惊讶的是,由于 MRO,A.__init__()中的super()调用实际上调用了B.__init__()(然后调用object.__init__())。
标签: python multiple-inheritance superclass super method-resolution-order