我一直在尝试理解super()
多重继承上下文中的行为。我很困惑为什么super()
test2.py 中父类中的调用会导致__init__()
父母双方都被调用?
测试1.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'>)
测试2.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'>)