Correct understanding and usage of super functions in Python Programming

Source: Internet
Author: User
Some people may think that why is there a super function in Python that can directly call the parent class method through the parent class name? In fact, many people have misunderstandings about the super function in Python, this article introduces the correct understanding and usage of the super function in Python programming. when the subclass needs to call the method of the parent class, the class method is called directly using the class name before python2.2, this is a non-bound class method, and the self object is passed as a parameter.

class A(object):   def say(self):     print 'I am A'  class B(A):   def say(self):     print 'I am B'     A.say(self)  b = B() b.say()

Output

I am BI am A

This operation is quite good, but there is a problem. when the parent class changes its name, we need to explicitly call the parent class one by one for correction. the coupling between the child class and the parent class is relatively high.
Therefore, python2.2 introduced the super () function to avoid hard encoding, without worrying about the name of the parent class.
Using the super () function, the above code can be written as follows.

class B(A):   def say(self):     print 'I am B'     super(B,self).say()

After python3.0, The super () function does not need to pass parameters, that is, the above line of code directly super (). say.

Notes:

  • Super can only be used in new classes.

  • Super has a problem with multi-inheritance. if the subclass inherits multiple parent classes, super calls the method of the first parent class.

  • Do not mix these two methods to call the parent class method, either using a non-bound class method or using super. Otherwise, it may be not called or called multiple times.

BUT:
Do not think of the parent class when talking about super! Super refers to the next class in MRO!
When talking about super, I thought of the parent class. this is a very easy mistake for beginners and also a mistake I made in the past.

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

The two parameters cls and inst do two things respectively:
1. inst is responsible for generating MRO list
2. use cls to locate the index in the current MRO and return the mro [index + 1]
These two things are the essence of super. remember them!
MRO stands for Method Resolution Order, which represents the sequence of class inheritance.

For example:

class Root(object):  def __init__(self):    print("this is Root")class B(Root):  def __init__(self):    print("enter B")    # print(self) # this will printsuper(B, self).__init__()    print("leave B")class C(Root):  def __init__(self):    print("enter C")    super(C, self).__init__()    print("leave C")class D(B, C):  passd = D()print(d.__class__.__mro__)

Output

enter Benter Cthis is Rootleave Cleave B(,,,,)

After we know that super and parent classes are not actually Associated, it is not difficult to understand why the next sentence of "enter B" is "enter C" instead of "this is Root" (if super stands for "calling the parent class method ", this is Root ). The process is as follows in the _ init _ function of B:

super(B, self).__init__()

First, we obtain self. _ class _. _ mro __. note that self is a D instance rather than B's

(

Then, use B to locate the index in MRO and find the next one. Apparently, the next part of B is C. Therefore, we call C's _ init __and Press enter C.

By the way, why does B _ init _ be called: because D does not define _ init __, the next class will be found in MRO, check whether it defines _ init __, that is, to call _ init _ of B __.

In fact, all the logic is very clear. The key is to understand what super has done.


The above is the correct understanding and usage of the super function in Python programming. For more information, see The PHP Chinese network (www.php1.cn )!

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.