class Foo: pass class Foo(object): pass
MRO:method resolution order 方法的查找順序 python
class Base: pass class Base1: def eat(self): pass class Bar(Base, Base1): pass b = Bar() # Bar --> Base -->Base1 b.eat()
二、經典類的MRO樹形結構的深度優先遍歷 -->樹形結構遍歷面試
class A: pass class B(A): pass class C(A): pass class D(B, C): pass class E: pass class F(D, E): pass class G(F, D): pass class H: pass class Foo(H, G): pass
畫圖算法
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 G(E): pass class H(G, F): pass
class Foo: def __init__(self,a,b,c): self.a = a self.b = b self.c = c class Bar(Foo): def __init__(self,a,b,c,d): super().__init__(a,b,c) # 訪問父類的構造方法 self.d = d b = Bar(1,2,3,4) print(b.__dict__) # {'a': 1, 'b': 2, 'c': 3, 'd': 4}
class Foo: def func1(self): super().func1() # 此時要找的是MRO順序中下一個類的func1()方法 print("個人老家就住在這個屯") class Bar: def func1(self): print("你的老家不在這個屯") class Ku(Foo,Bar): def func1(self): super().func1() # 此時super找的是Foo print("他的老家不知道在哪一個屯") k = Ku() # 先看MRO,Ku,Foo,Bar,object k.func1() # 你的老家不在這個屯 # 個人老家就住在這個屯 # 他的老家不知道在哪一個屯
# MRO + super 面試題 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): def __init__(self, val): super(Incr, self).__init__(val) self.val+= 1 # Incr Pro Add2 Mult HaHa Init p = Incr(5) print(p.val) c = Add2(2) print(c.val) # Add2 # Mult # 哈哈 # init # 5.0 # 8.0 # Add2 # init # 2 # 4