Use of super () in Python (i)

Source: Internet
Author: User

1.super was introduced to the original intention

Super () is usually said to be super function, in fact it is a built-in class, is a new addition in Python2.2, Super () to instantiate a Super object, the Super object acts as an Access Proxy, it helps the object of the subclass to access the parent class, Grandfather classes and all ancestor classes are methods (especially those that access the quilt class overrides).

Before the super class did not appear, if you want to call the method of the parent class in the subclass method, you must explicitly use the class name of the parent class to invoke it in a non-binding way. The following example (all example programs are implemented under Python3.4) is shown below:

class A (): def __init__ print ( " enter A " ) print ( " leave A " )

class B (A): def __init__ (self): Print ("enter B") A. __init__ (self) Print ("leave b") >>> b = B () Enter B Enter a leave a leave B

While using A. __init__ (self) to invoke the method of the parent class, but one potential problem is that if the parent of B becomes another class such as C, then the original code will need to be modified to C. __init__ (self), this would be a tedious task if the code volume is huge. If you can have a statement, it does not need to explicitly use the name of the parent class, it only needs to pass in the current class name, the current class instance, you can automatically calculate the parent class, so you can flexibly deal with the changes in class structure. The super (b,self). __init__ () statement can be an appropriate substitute for a. __init__ (self) statement.

Python also supports multiple inheritance, using a in multiple inheritance . __init__ (self) This method of invoking the ancestor class will also produce a situation where the methods of the ancestor class are repeatedly called repeatedly, which can also cause potential problems.

classA ():defHello (self):Print("Enter A")        Print("Leave A")classB (A):defHello (self):Print("Enter B") A.hello (self)Print("Leave B")classC (A):defHello (self):Print("Enter C") A.hello (self)Print("Leave C")classD (B, C):defHello (self):Print("Enter D") B.hello (self) C.hello (self)Print("Leave D") d=D () D.hello ()

The result of the operation is:

Enter denter benter aleave aleave benter CEnter aleave aleave CLeave D
Obviously, the hello () function in a is executed two times, according to a d,b,a, c,a in such a order. This is not the order in which we want the code to execute in some cases. In more cases, we may require that the methods in the ancestor class be called in a sequence (the MRO sequence, the current Python version is using the C3 algorithm). For example: Call the Hello () method in the order of D,b,c,a.

The above effect can be achieved with the proper use of super.

classA ():defHello (self):Print("Enter A")        Print("Leave A")classB (A):defHello (self):Print("Enter B") Super (B, self). Hello ()Print("Leave B")classC (A):defHello (self):Print("Enter C") Super (C, self). Hello ()Print("Leave C")classD (B, C):defHello (self):Print("Enter D") Super (D, self). Hello ()Print("Leave D") d=D () D.hello ()

Operation Result:

Enter denter benter CEnter aleave aleave CLeave bleave D

The B.hello (self) of the Hello function in class D involving multiple inheritance, the C.hello (self) Two statement was replaced by super (D, self). Hello () Instead, the statement in class B,c also uses Super statement. This allows the code to automatically jump to the corresponding next function, especially super (b, self) in class B. Hello (), the value of self is d, calculated by D and B (with C3

algorithm to calculate) the next function to be called is the Hello code in Class C, which completes the key "jump" rather than taking it for granted to invoke the code in a. However, super "jump" when dealing with multiple inheritance, but also bring unexpected trouble,

is called the function, the value mismatch problem, the origin of this problem or super itself mechanism, in the above class B as an example, when writing the Code of Class B, when using super () we will certainly follow the parameters of the method in his parent class A to pass the value, but when the code runs, The method in B will call the method in C instead of the method in a, which may result in a pass-through error when calling the method.

Next, use an example to illustrate the possible drawbacks of a method being repeated:

The effect on D may be different if D is treated as data and the number of times the code in the class is handled differently.

classA ():defAdd (self): Self.data.append ("Letter A") Self.count+ = 1classB (A):defAdd (self): Self.data.append ("Letter B") Self.count+ = 1Super (B, self). Add ()classC (A):defAdd (self): Self.data.append ("Letter C") Self.count+ = 1Super (C, self). Add ()classD (B, C):def __init__(self): Self.count=0 Self.data= []    defAdd (self): Self.data.append ("Letter D") Self.count+ = 1Super (d, Self). Add () d=D () d.add ()Print(D.count)Print(D.data)

Operation Result:

4[' letterD'letterB'letterC ' ' Letter A ']

If you do not use super and call the parent class in a non-binding way:

classA ():defAdd (self): Self.data.append ("Letter A") Self.count+ = 1classB (A):defAdd (self): Self.data.append ("Letter B") Self.count+ = 1A.add (self)classC (A):defAdd (self): Self.data.append ("Letter C") Self.count+ = 1A.add (self)classD (B, C):def __init__(self): Self.count=0 Self.data= []    defAdd (self): Self.data.append ("Letter D") Self.count+ = 1B.add (self) c.add (self) d=D () d.add ()Print(D.count)Print(D.data)

Operation Result:

5['letter D'letterB' letterA ' ' Letter C ' ' Letter A ']

D ran a more "letter a" result, and Count added one.

Summary:

Written so much, in fact, it can be attributed to two points.

There is no super before involved because of the modification of class inheritance resulting from the modification code, more cumbersome, with super after no modification.

Super allows you to access the parent class in the subclass method, and also allows you to inherit the method of the tree in an orderly, non-repetitive way.

Use of super () in Python (i)

Related Article

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.