The super function in Python understands

Source: Internet
Author: User
The super () function works according to the two parameters that are passed in:

The class name passed in by the first parameter determines where in the MRO is currently located. MRO (Method Resolution Order);

The current MRO list is determined by self, which is passed in the second argument.

Def super (CLS, inst):    MRO = INST.__CLASS__.MRO () #确定当前MRO列表    return Mro[mro.index (CLS) + 1] #返回下一个类

The following code:

Class A (object):  def name:    print (' name is Xiaoming ')    #super (a,self). Name () class B (object):  def name:    print (' name is Cat ') class C (A, B):  def name:    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 executing the super () function under Class C, the name function under Class A is actually called. The super () function is commented out in a, so it does not go back to execution. and print out the current MRO list order of C,a,b,object.

(<class ' __main__. C ';, <class ' __main__. A ';, <class ' __main__. B ';, <class ' object ' >) name is Wangname is xiaoming

When we remove the annotations in Class A, we execute the code output: As you can see, after a executes, the name () function in B continues to execute. If there is still a super function in B, it will continue to look up for the name () function in object.

(<class ' __main__. C ';, <class ' __main__. A ';, <class ' __main__. B ';, <class ' object ' >) name is Wangname are Xiaomingname is cat


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.