Home > Article > Backend Development > Understanding the super function in Python
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 wang name 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 wang name is xiaoming name is cat
For more articles related to understanding the super function in Python, please pay attention to the PHP Chinese website!