参考资料:Python super() 函数 和object的理解
参考资料: super的理解和使用
- 需要知道 super 是一个类,调用super()相当于创建一个对象。
- 在Python中,每个类都有一个mro的类方法,返回的是一个祖先类的列表。(MRO(method resolution order):表示了类继承体系中的成员解析顺序。)
class Root():
def __init__(self):
print("this is Root")
class B(Root):
def __init__(self):
print("---> enter B")
# super(B, self).__init__()
# 等效与:
temp = super(B,self)
temp.__init__()
print('temp is B type?',isinstance(temp,B))
print('temp is Root type?',isinstance(temp,Root))
print('temp is super type?',isinstance(temp,super))
print("<--- leave B")
b = B()
print('MRO of b :',b.__class__.__mro__)
输出如下:
---> enter B this is Root temp is B type? False temp is Root type? False temp is super type? True <--- leave B MRO of b : (, , )
- Python3的类(类默认继承了object——新式类)默认按照“广度优先”搜索父类的方法(而Python2中未继承object类的类称为经典类,经典类默认按照“深度优先”搜索父类的方法)
class A:
def f(self):
print('A')
super(A, self).f()
class B(A):
def f(self):
print('B')
super(B, self).f()
class C(A):
def f(self):
print('C')
super(C, self).f()
class X:
def f(self):
print('X')
class Y(X):
def f(self):
print('Y')
super(Y, self).f()
class Foo(B,C,Y):
pass
foo = Foo()
foo.f()
Python3 按照“广度优先”搜索,输出如下:
B C A Y X



