Home >Backend Development >Python Tutorial >Understanding the super function in Python

Understanding the super function in Python

高洛峰
高洛峰Original
2017-02-18 10:48:101235browse

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 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 &#39;__main__.C&#39;>, <class &#39;__main__.A&#39;>, <class &#39;__main__.B&#39;>, <class &#39;object&#39;>)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!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn