current position:Home>Why do Python classes inherit object classes

Why do Python classes inherit object classes

2022-06-24 08:33:18zero000

inherit

python class Be sure to inherit object Class? ? Why? ?

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 :

  1. https://www.zhihu.com/question/19754936
  2. https://stackoverflow.com/questions/4015417/why-do-python-classes-inherit-object

copyright notice
author[zero000],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/175/20210623205303702a.html

Random recommended