程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Why do Python classes inherit object classes

編輯:Python
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

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved