假设我有一个多继承场景:
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?
Run Code Online (Sandbox Code Playgroud)
有写作两种典型的方法C的__init__:
ParentClass.__init__(self)super(DerivedClass, self).__init__()但是,在任何一种情况下,如果父类(A和B)不遵循相同的约定,则代码将无法正常工作(某些可能会被遗漏,或被多次调用).
那么又是什么样的正确方法呢?很容易说"只是保持一致,遵循一个或另一个",但如果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 …Run Code Online (Sandbox Code Playgroud)