以下是我的情况,我应该写什么来代替评论?
提前谢谢你,如果我问了一些问题,我很抱歉。
我已经找到答案,但没有成功。
#!/usr/bin/python3.4
class A(object):
def __init__(self):
print("A constructor")
class B(A):
def __init__(self):
super(B, self).__init__()
print("B constructor")
class C(A):
def __init__(self):
super(C, self).__init__()
print("C constructor")
class D(B,C):
def __init__(self):
""" what to put here in order to get printed:
B constructor
C constructor
A constructor
D constructor
or
C constructor
B constructor
A constructor
D constructor
?
(notice I would like to print once 'A constructor')
"""
print("D constructor")
if __name__ == "__main__":
d = D()
答案 0 :(得分:1)
我发现改变一点类构造函数代码可以满足我的需求:
#!/usr/bin/python3.4
class A(object):
def __init__(self):
print("A constructor")
class B(A):
def __init__(self):
if self.__class__ == B:
A.__init__(self)
print("B constructor")
class C(A):
def __init__(self):
if self.__class__ == C:
A.__init__(self)
print("C constructor")
class D(B,C):
def __init__(self):
B.__init__(self) #
C.__init__(self) # if B constructor should be
A.__init__(self) # called before of C constructor
print("D constructor") #
# C.__init__(self) #
# B.__init__(self) # if C constructor should be
# A.__init__(self) # called before of B constructor
# print("D constructor") #
if __name__ == "__main__":
d = D()