Home  >  Article  >  Backend Development  >  How does the super function in Python implement inheritance?

How does the super function in Python implement inheritance?

不言
不言forward
2019-03-06 15:21:472010browse

The content of this article is about how to implement inheritance of the super function in Python? It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

A big difference between Py 2.x and Py 3.x is classes, whether it is class definition or class inheritance. Class inheritance in Py 3.x can directly use the super() keyword instead of the original super(Class, self).

So what is super() based on? Let’s analyze it today.

The super() function has the following specific functions based on the two parameters passed in:

The class name passed in as the first parameter determines the current position in the MRO. MRO (Method Resolution Order);

Determine the current MRO list through self passed in as the second parameter.

def super(cls, inst):
   mro = inst.__class__.mro() #确定当前MRO列表
   return mro[mro.index(cls) + 1] #返回下一个类

The following code:

class A(object):
    def name(self):
        print('name is xiaoming')    
        #super(A,self).name()

class B(object): 
    def name(self):
        print('name is cat')
      
class C(A,B):
    def name(self):
        print('name is wang')
        super(C,self).name()if __name__ == '__main__':

c = C()
print(c.__class__.__mro__)
c.name()

Execute the above code output: When the super() function under class C is executed, the name function under class A is actually called. The super() function is commented out in A, so execution does not continue backwards. And the current MRO list order is printed out as C,A,B,object.

(<class &#39;__main__.C&#39;>, <class &#39;__main__.A&#39;>, <class &#39;__main__.B&#39;>, <class &#39;object&#39;>)name is wangname is xiaoming

When we remove the comments in class A, the execution code output: You can see that when A is executed, execution continues The name() function in B. If there is still a super function in B, it will continue to look up to see if there is a name() function in object.

(<class &#39;__main__.C&#39;>, <class &#39;__main__.A&#39;>, <class &#39;__main__.B&#39;>, <class &#39;object&#39;>)name is wangname is xiaomingname is cat

The above is the detailed content of How does the super function in Python implement inheritance?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:Python. If there is any infringement, please contact admin@php.cn delete