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 '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <class 'object'>)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 '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <class 'object'>)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!