继承和super()
1. 了解python2和python3类的区别
python2在2.3之前使用的是经典类, 2.3之后, 使用的是新式类
class Foo:
pass
class Foo(object):
pass
MRO: method resolution order 方法的查找顺序
class Base:
def chi():
pass
class Base1:
def chi():
pass
class Bar(Base, Base1):
pass
b = Bar() # Bar -> Base -> Base1
b.chi()
2. 经典类的MRO 树形结构的深度优先遍历 -> 树形结构遍历
3. 新式类的MRO C3算法(难点, 重点)
class A: pass class B(A): pass class C(A): pass class D(B, C): pass class E(C, A): pass class F(D, E): pass class M: pass class N(M): pass class P(E, A): pass class X: pass class Q(P,N,X): pass class G(Q, F): pass class H(G, F): pass
print(H.__mro__)
步骤:
1. 拆分
2. 合并
用头和身体比较:
# 加法:merge(), 拿第一项的第一位和 后面每项的除了第一位比较. 如果没有出现, 则该位元素算出
如果出现了. 此时开始下一项的第一位继续和后面每一项的除了第一位比较:
用头和后面身体比较
求H的MRO
设求MRO的算法是L
L(H) = H + L(G) + L(F) + GF # HGQPFDBECANMX
L(G) = G + L(Q) + L(F) + QF # GQPFDBECANMX
L(Q) = Q + L(P) + L(N) + L(X) + PNX # QPECANMX
L(P) = P + L(E) + L(A) + EA # PECA
L(E) = E + L(C) + L(A) + CA # ECA
L(C) = C + L(A) + A # CA
L(A) = A # A
L(N) = N + L(M) + M # NM
L(M) = M # M
L(X) = X # X
L(F) = F + L(D) + L(E) + DE # FDBECA
L(D) = D + L(B) + L(C) + BC # DBCA
L(B) = B + L(A) + A # BA
4. super() 找MRO顺序的下一个
class Init(object): def __init__(self, v): print("init") self.val = v class Add2(Init): def __init__(self, val): print("Add2") super(Add2, self).__init__(val) print(self.val) self.val += 2 class Mult(Init): def __init__(self, val): print("Mult") super(Mult, self).__init__(val) self.val *= 5 class HaHa(Init): def __init__(self, val): print("哈哈") super(HaHa, self).__init__(val) self.val /= 5 class Pro(Add2,Mult,HaHa): pass class Incr(Pro): # incr->pro->add2->Mult->HaHa->init def __init__(self, val): # 5 super(Incr, self).__init__(val) self.val += 1 p = Incr(10) print(p.val)
先求出Incr的MRO的顺序
# incr->pro->Add2->Mult->HaHa->Init
#先走Incr的super(),Pro为pass,直接进入MRO的下一个Add2,打印出"Add2",
#在走下一个Mult,打印出"Mult",在走HaHa,打印"哈哈",在走下一个Init,
#打印"Init",并给变量赋值5,在HaHa中变量 /=5 ,变量为2.0,再执行Mult,
#变量 *=5 ,变量为10.0,继续执行Add2,打印变量为"10.0",并对变量 +=2,
#变量为12.0,继续执行Pro,Pro为pass,继续执行Incr,变量 +=1,打印变量为"13.0".
#最后得出结果为 "Add2" > "Mult" > "哈哈" > "Init" > "10.0" > "13.0"