说我有一个多继承场景:
class A(object):
# code for A here
class B(object):
# code for B here
class C(A,B):
def __init__(self):
# What's the right code to write here to ensure
# A.__init__ and B.__init__ get called?
有两种典型的方法来编写C的__init__:
>(old-style)ParentClass .__ init __(self)
>(newer-style)super(DerivedClass,self).__ init __()
那么,什么是正确的方法呢?很容易说“只是一致,遵循一个或另一个”,但如果A或B来自第三方库,那么呢?是否有一种方法可以确保所有父类构造函数被调用(并且以正确的顺序,并且只有一次)?
编辑:看看我的意思,如果我做:
class A(object):
def __init__(self):
print "entering A"
super(A, self).__init__()
print "leaving A"
class B(object):
def __init__(self):
print "entering B"
super(B, self).__init__()
print "leaving B"
class C(A,B):
def __init__(self):
print "entering c"
A.__init__(self)
B.__init__(self)
print "leaving c"
然后我得到:
entering c
entering A
entering B
leaving B
leaving A
entering B
leaving B
leaving c
注意,B的init被调用两次。如果我做:
class A(object):
def __init__(self):
print "entering A"
print "leaving A"
class B(object):
def __init__(self):
print "entering B"
super(B, self).__init__()
print "leaving B"
class C(A,B):
def __init__(self):
print "entering c"
super(C, self).__init__()
print "leaving c"
然后我得到:
entering c
entering A
leaving A
leaving c
注意,B的init永远不会被调用。所以看来,除非我知道/控制我继承的类(A和B)的init,我不能为我写的类(C)做一个安全的选择。