类A,
类B,C均继承于A
类D继承与(B, C)
代码如下:
class A:
def __init__(self, a):
print("Enter A")
self.a = a
print("Leave A")
class B(A):
def __init__(self, a, b):
print("Enter B")
super(B, self).__init__(a)
self.b = b
print("Leave B")
class C(A):
def __init__(self, c):
print("Enter C")
super(C, self).__init__(a)
self.c = c
print("Leave C")
上面的感觉没有问题,但是到D的时候:
class D(A, B, C):
def __init__(self, a, b, c, d):
print("Enter D")
super(D, self).__init__(…) # here!
self.__d = d
print("Leave D")
def __str__(self):
return "Class D: a =" + str(self.a) + " b = " + str(self.b) \
+ " c = " + str(self.c) + " d = " + str(self.__d)
在super这里我刚开始不知道怎么写,因为D继承了B和C,那么super返回的是B还是C?
查了资料我知道了所谓的MRO,会将D上面的所有类都初始化一遍,于是将类D的super修改如下:
尝试1:
super(D, self).__init__(a, b, c)
对于main:
`
def main():
# aClass = A(2)
# print(aClass)
# bClass = B(3, 4)
# print(bClass)
dClass = D(5, 6, 7, 8)
print(dClass.b)
print(dClass)
main() # Call the main function.
结果运行结果是:
Enter D
Traceback (most recent call last):
File “2.py”, line 50, in
main() # Call the main function.
File “2.py”, line 46, in main
dClass = D(5, 6, 7, 8)
File “2.py”, line 33, in init
super(D, self).init(a, b, c)
TypeError: init() takes 3 positional arguments but 4 were given`
尝试2:给B类添加一个参数c,(猜测参数c会先传给D->B->C)将B类修改如下:
class B(A):
def __init__(self, a, b, c):
print("Enter B")
super(B, self).__init__(a, c)
self.b = b
print("Leave B")
def __str__(self):
return "Class B: a = " + str(self.a) + " b = " + str(self.b)
运行成功,结果是:
Enter D
Enter B
Enter C
Enter A
Leave A
Leave C
Leave B
Leave D
6
Class D: a =5 b = 6 c = 7 d = 8```
至此,D类大概是没有问题了,但是仍然感觉B类这样很奇怪,
**问题1**:请问可以这样用吗?我是根据报错信息一次一次尝试猜测出这样一种方法。
**问题2**:感觉上好像B类这样定义跟B类的初衷不太符合,这样的B类是否可以单独拿出来创建自己的对象?
**尝试3**:单独创建一个B类的对象bClass:
def main():
# aClass = A(2)
# print(aClass)
bClass = B(3, 4)
“`
报错如下:
bClass = B(3, 4)
TypeError: init() missing 1 required positional argument: ‘c’
到此为止,我想不出什么解决的办法了,
**问题3:如果我前面的步骤是对的,那么是否可以这样理解,super使得D, B, C, A按照MRO的顺序链接绑定到了一起,这样最终D的对象可以被成功创建,并且各父类均只初始化一次,但是代价就是,各父类A, B, C不能再单独创建自己的对象?
问题4:如果这不是正确的方法,请问应该怎么做**