Inherit object Class is a new class , No inheritance object Class is a classic class , stay Python 2.7 There will be differences between the new class and the classic class in terms of multiple inheritance :
class A: def foo(self): print('called A.foo()') class B(A): pass class C(A): def foo(self): print('called C.foo()') class D(B, C): pass if __name__ == '__main__': d = D() d.foo()
B、C yes A Subclasses of ,D More inherited B、C Two classes , among C Rewrote A Medium foo()
Method .
If A It's a classic class ( Code above ), When calling D Instance foo() When the method is used ,Python According to Depth first The way to search foo() , The path is a B-A-C , Execution is A Medium foo() ;
If A It's new , When calling D Instance foo() When the method is used ,Python Will press Photo breadth first The way to search foo() , The path is a B-C-A , Execution is C Medium foo() . because D It's direct inheritance C Of , Logically speaking , perform C Medium foo() It is more reasonable , Therefore, the handling of multi inheritance by new classes is more logical .
stay Python 3.x The new classes in seem to be compatible with the classic classes , No matter what A Whether to inherit object class , D In the instance foo() It will be carried out C Medium foo() . But in Python 2.7 There is still a difference in , Therefore, the new class is recommended , Inheritance object class .
Reference resources :
說明:這是一個機器學習實戰項目(附帶數據+代碼+文檔+視頻講