Python: super

Source: Internet
Author: User
Python: super

Getting started with super ()

In class inheritance, If you redefine a method, this method will overwrite the method of the same name as the parent class, but sometimes we want to implement the function of the parent class at the same time, we need to call the method of the parent class, which can be implemented by using super, for example:

Class Animal (object): def _ init _ (self, name): self. name = name def greet (self): print 'Hello, I am % s. '% self. nameclass Dog (Animal): def greet (self): super (Dog, self ). greet () # Python3 can use super (). greet () print 'wangwang...'

In the above example, Animal is the parent class and Dog is the Subclass. we redefine the greet method in the Dog class. in order to simultaneously implement the function of the parent class, we call the method of the parent class, see the following usage:

>>> dog = Dog('dog')>>> dog.greet()Hello, I am dog.WangWang..

The most common usage of super is to call the initialization method of the parent class in the subclass, for example:

Class Base (object): def _ init _ (self, a, B): self. a = a self. B = bclass A (Base): def _ init _ (self, a, B, c): super (A, self ). _ init _ (a, B) # super () can be used in Python3 (). _ init _ (a, B) self. c = c

Go deep into super ()

After reading the above usage, you may think that super is easy to use. it is nothing more than getting the parent class and calling the method of the parent class. In fact, in the above case, the class obtained by super is just a parent class, but it is not necessarily the case in other cases. super actually has no substantive association with the parent class.

Let's take a look at a slightly complex example that involves multiple inheritance. the code is as follows:

class Base(object):    def __init__(self):        print "enter Base"        print "leave Base"class A(Base):    def __init__(self):        print "enter A"        super(A, self).__init__()        print "leave A"class B(Base):    def __init__(self):        print "enter B"        super(B, self).__init__()        print "leave B"class C(A, B):    def __init__(self):        print "enter C"        super(C, self).__init__()        print "leave C"

Base is the parent class, A and B are inherited from Base, and C are inherited from A and B. Their inheritance relationships are as follows:

      Base      /  \     /    \    A      B     \    /      \  /       C

Now, let's take a look at the usage:

>>> c = C()enter Center Aenter Benter Baseleave Baseleave Bleave Aleave C

If you think super stands for "calling the parent class method", you may wonder why the next sentence of "enter A" is not "enter Base" but "enter B. The reason is that there is no substantial correlation between super and its parent class. now let's figure out how super works.

MRO list

In fact, for each class you define, Python calculates a Method Resolution Order (MRO) list, which represents the sequence of class inheritance, we can use the following method to obtain the MRO list of a class:

>>> C.mro()   # or C.__mro__ or C().__class__.mro()[__main__.C, __main__.A, __main__.B, __main__.Base, object]

Then how is the order of the MRO list determined? it is implemented through a C3 linear algorithm. here we will not go into this algorithm, interested readers can take a look at it by themselves. In general, the MRO list of a class is to merge the MRO list of all parent classes and follow the following three principles:

The subclass is always before the parent class.

If multiple parent classes exist, they are checked according to their order in the list.

If you have two valid options for the next class, select the first parent class.

Super principle

Super works as follows:

def super(cls, inst):    mro = inst.__class__.mro()    return mro[mro.index(cls) + 1]

Among them, cls represents the class, inst represents the instance, and the above code does two things:

Get the MRO list of inst

Search for the index of cls in the current MRO list and return its next class, that is, mro [index + 1].

When you use super (cls, inst), Python searches for the next cls class in the MRO list of inst.

Now let's go back to the previous example.

First, let's look at the _ init _ method of Class C:

super(C, self).__init__()

Here, self is the current C instance, and the result of self. _ class _. mro () is:

[__main__.C, __main__.A, __main__.B, __main__.Base, object]

As you can see, the next class of C is A, so it jumps to _ init __of A. Then, enter A is printed and the following line of code is executed:

super(A, self).__init__()

Note: The self here is also the current C instance. the MRO list is the same as above. search for the next class of A in MRO and find it is B, jump to _ init __of B, and enter B is printed instead of enter Base.

The entire process is clear. The key is to understand how super works, rather than taking it for granted that super calls the method of the parent class.

Summary

In fact, there is no substantial association between super and parent classes.

Super (cls, inst) obtains the next class of cls in the MRO list of inst.

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.