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

Inheritance mechanism of Python

編輯:Python

One 、python Inheritance

python Single inheritance and multiple inheritance are supported , This inheritance mechanism greatly improves the reusability of code , Enable subclasses to inherit methods and properties of parent and ancestor classes , This is inheritance , meanwhile , Subclasses can also override certain methods or properties of the parent and ancestor classes , This allows subclasses to behave differently from their parent and ancestor classes , This is polymorphism .

python As a support oop Language , Its class( class ) Realized encapsulation , Inheritance mechanism realizes inheritance and polymorphism .

 

One of the most important aspects of inheritance is polymorphism , When a subclass has the same properties or methods as its parent and ancestor ,python Which method or property will be called .

Be careful :python2 And python3 The multiple inheritance mechanism is different . stay python2 There are two types of inheritance : If it is a classic class ( The base class is not from object Derived from ) The inheritance of is depth first ; If it's a new class ( Base class from object Derived from ), Then the inherited parent class is derived from the same base class , Then breadth first ; If the inherited parent class derives from a different base class , Then the traversal sequence is more complex , It's explained in detail later . stay python3 The classic class , therefore python3 Only the inheritance of new classes in .

1、 Single inheritance

In single inheritance , When we pass subclasses .xxxx When calling an instance method or accessing a property ,python First, we will look for the method or attribute in the subclass , If you can't find it, go to the parent class . If the method or property is not found in the parent class , Just keep looking recursively ( Go to the parent class of the parent class to find , And so on . Here we need to pay attention to : When searching recursively , If the parent class is still single inheritance, search according to the single inheritance method , If the parent class is multi inheritance, search according to the multi inheritance method .), Until we found one named xxxx Method or property of , Or until Object This class .

2、 Multiple inheritance

More inheritance , When we pass subclasses .xxxx When calling an instance method or accessing a property ,python They will search the parent class in a certain order . The sequence is obtained by a certain algorithm , In the example, you can use xxx.__class__.__mro__ Get this search order list .

Calculation MRO The algorithm of :

class C Linearization of (MRO) Write it down as L[C] = [C1, C2,…,CN]. among C1 be called L[C] The head of the , The rest of the elements [C2,…,CN] Called tail . If a class C Inherited from base class B1、B2、……、BN, Then we can calculate according to the following two steps L[C]:

  1. L[object] = [object]

  2. L[C(B1…BN)] = [C] + merge(L[B1]…L[BN], [B1]…[BN])

The key here is merge, Its input is a set of lists , Output a list as follows :

  1. Check the header element of the first list ( Such as L[B1] The head of the ), Write it down as H.
  2. if H Does not appear at the end of other lists , Then output it , And remove it from all lists , Then go back to step 1; otherwise , Take the header of the next list and mark it as H, Continue with this step .
  3. Repeat the above steps , Until the list is empty or no more elements can be found for output . In the former case , Then the algorithm ends ; In the latter case , Description cannot build inheritance relationship ,Python It throws an exception TypeError.

quote :https://blog.csdn.net/lengye7/article/details/121312262

The above statement is quite abstract , Let's see 3 An example .

1、 Complete single inheritance example

class base:
def hello(self):
print("hello base!")
class type1(base):
def hello(self):
print("hello type1!")
class type2(base):
def hello2(self):
print("hello type2!")
a = type1()
a.hello()
b = type2()
b.hello()
b.hello2()

Inheritance diagram : 

The above code execution results :

  Execute to a.hello(), because a yes type1 Example ,type1 There are hello Method , therefore python Call directly type1 Medium hello Method , Output hello type1!.

Execute to b.hello(), because b yes type2 Example ,type2 Not available in hello Method , therefore python Deparent class base In search of , In the parent class base Find hello Method and execution , Output hello base!.

Execute to b.hello2(), because b yes type2 Example ,type2 There are hello2 Method ,python Direct execution hello2, Output hello type2!.

2、 Examples of multiple inheritance

1)、 The right example

class base:
test = "test_base"
def hello(self):
print("hello base!",self.test)
class type1(base):
test = "test_type1"
def hello(self):
print("hello type1!",self.test)
class type2(base):
def hello2(self):
print("hello type2!")
class type3(type2,type1):
def hello3(self):
print("hello type3!")
c = type3()
c.hello()
c.hello2()
c.hello3()
print(c.__class__.__mro__)

We can infer its MRO:[type3,type2,type1,base,object].

Running results :

 2)、 Examples of mistakes

Form like ,class test1(X,A,B).....,q among X yes A perhaps B The base class of any parent class , You will not be able to build MRO, Report errors .

class base:
test = "test_base"
def hello(self):
print("hello base!",self.test)
class type1(base):
test = "test_type1"
def hello(self):
print("hello type1!",self.test)
class type2(base):
def hello2(self):
print("hello type2!")
class type3(base,type2,type1):
def hello3(self):
print("hello type3!")
c = type3()
c.hello()
c.hello2()
c.hello3()
print(c.__class__.__mro__)

Running results :

Can't build MRO.

Form like :class test(A,B,C):......, among A Of MRO in [...,X,...,Y...],B Of MRO in [...,Y,...,X,...], Will not be able to build MRO, To report a mistake .

class base:
test = "test_base"
def hello(self):
print("hello base!",self.test)
class type1(base):
test = "test_type1"
def hello(self):
print("hello type1!",self.test)
class type2(base):
def hello2(self):
print("hello type2!")
class type3(type2,type1):
def hello3(self):
print("hello type3!")
class type4(type1,type2):
pass
class type5(type4,type3):
pass
c = type5()
c.hello()
c.hello2()
c.hello3()
print(c.__class__.__mro__)

  Running results :

Can't build MRO. 


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