Understanding of super functions in Python

Source: Internet
Author: User
The super function in Python understands the specific functions of the super () function based on the two parameters passed in:

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

Use the self passed in by the second parameter to determine the current MRO list.

Def super (cls, inst): mro = inst. _ class __. mro () # determine the current MRO list return mro [mro. index (cls) + 1] # returns the next class

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()

Run the above code output: when the super () function in class C is executed, the name function in Class A is actually called. The super () function is commented out in A, so it is not executed backward. The current MRO list is printed in the order of C, A, B, and object.

(
 
  , 
  
   , 
   
    , 
    
     )name is wangname is xiaoming
    
   
  
 

After removing the comments in class A, run the code output: you can see that the name () function in class B is executed after Class A is executed. If the super function still exists in B, the system continues to look up whether the object has the name () function.

(
 
  , 
  
   , 
   
    , 
    
     )name is wangname is xiaomingname is cat
    
   
  
 


For more articles on understanding the super function in Python, refer to the PHP Chinese website!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.