Python面向对象中super用法与MRO机制
最近再看trackformer,里面用到了super的用法,记录一下super的用法
class A(object):
def __init__(self):
print('init A')
def fun(self):
print('A.fun')
print(self)
super(A, self).fun()
class B(object):
def __init__(self) :
print('init B')
def fun(self):
print('B.fun')
class C(object):
def __init__(self):
print('init C')
def fun(self):
print('C.fun')
class D(A,B):
def __init__(self):
print('init D')
def fun(self):
print('D.fun')
print(self)
super(D, D()).fun()
class E(B, C):
def __init__(self):
print('init E')
def fun(self):
print('E.fun')
super().fun()
class F(D, E):
def __init__(self):
print('init F')
def fun(self):
print('F.fun')
print(self)
super().fun()
f = F()
f.fun()
# putput
init F
F.fun
<__main__.F object at 0x7f75377a1850>
D.fun
<__main__.F object at 0x7f75377a1850>
init D
A.fun
<__main__.D object at 0x7f75377a1910>
B.fun
super().fun()等价于super(class_, self).fun()