在这里你可以看到具有相同方法的类是如何被调用的:-
这里,在 D(A,B,C) 类的方法 'feat()' 中
super(D, self).feature2() ----> 会调用A类的方法(feature2)。
super(A, self).feature2() ----> 会调用B类的方法(feature2)。
super(B, self).feature2() ----> 会调用C类的方法(feature2)。
class A:
def __init__(self):
print("in A Init")
def feature1(self):
print("Feature 1-A working")
def feature2(self):
print("Feature 2-A working")
class B:
def __init__(self):
print("in B Init")
def feature1(self):
print("Feature 1-B working")
def feature2(self):
print("Feature 2-B working")
class C:
def __init__(self):
print("in C Init")
def feature1(self):
print("Feature 1-C working")
def feature2(self):
print("Feature 2-C working")
class D(A,B,C):
def __init__(self):
super().__init__()
print("in D init")
def feat(self):
super(D, self).feature2()
super(A, self).feature2()
print('\n\n')
### B().feature2() is calling explicitly, but
### super(A, self).feature2() is not.
### Both will give same result in below,
### It will print True below
print(B().feature2() == super(A, self).feature2())
print('\n\n')
super(B, self).feature2()
print(D.__mro__)
a1 = D()
a1.feat()
结果是:-
in A Init
in D init
Feature 2-A working
Feature 2-B working
in B Init
Feature 2-B working
Feature 2-B working
True
Feature 2-C working
(<class '__main__.D'>, <class '__main__.A'>, <class '__main__.B'>, <class
'__main__.C'>, <class 'object'>)