Example of super keyword usage in Python

Source: Internet
Author: User
Tags builtin
This article mainly introduces the usage of the super keyword in Python. The example analyzes the function and related usage skills of the super keyword. If you need it, refer to the example in this article to describe the usage of the super keyword in Python. Share it with you for your reference. The specific analysis is as follows:

In the method of a Python class, to call a method of the parent class, before Python 2.2, the usual method is as follows:

Code Segment 1:

class A:def __init__(self):  print "enter A"  print "leave A"class B(A):def __init__(self):  print "enter B"  A.__init__(self)  print "leave B">>> b = B()enter Benter Aleave Aleave B

That is, use non-bound class methods (Methods referenced by class names), and introduce the objects to be bound (self) in the parameter list to call the parent class.

The disadvantage is that when the parent class of A subclass changes (for example, when the parent class of Class B changes from A to C), the entire class definition must be traversed, replace all the class names of non-bound methods, such as code snippet 2,

Code Segment 2:

class B(C):  # A --> Cdef __init__(self):  print "enter B"  C.__init__(self) # A --> C  print "leave B"

If the code is simple, such changes may be acceptable. However, if the code volume is large, such modifications may be disastrous. It is easy to cause a modification error.

Therefore, since Python 2.2, Python has added a keyword "super" to solve this problem. The official documentation for Python 2.3 is as follows:

super(type[, object-or-type])Return the superclass of type. If the second argument is omitted the super objectreturned is unbound. If the second argument is an object, isinstance(obj, type) must be true. If the second argument is a type, issubclass(type2, type) must be true. super() only works for new-style classes.A typical use for calling a cooperative superclass method is:  class C(B):    def meth(self, arg):      super(C, self).meth(arg)New in version 2.2.

From the description, we can rewrite Class B as code Segment 3:

Code Segment 3:

class A(object):  # A must be new-style classdef __init__(self):  print "enter A"  print "leave A"class B(C):   # A --> Cdef __init__(self):  print "enter B"  super(B, self).__init__()  print "leave B"

Try to execute the same code above, and the results are consistent, but there is only one modified code, which minimizes the maintenance of the Code, which is a good usage. Therefore, in our development process, the super keyword is widely used and has always performed well.

1. super is not a function. It is a class name. For example, super (B, self) actually calls the initialization function of the super class and generates a super object;

2. The super class initialization function does not perform any special operations, but simply records the class type and specific instance;

3. The call of super (B, self). func is not used to call the func function of the parent class of the current class;

4. multiple inheritance classes in Python use mro to ensure that the functions of each parent class are called one by one, and that each parent class function is called only once (if each class uses super );

5. mixing super classes and unbound functions is a dangerous action, which may cause the parent class function to be called not to be called or a parent class function to be called multiple times.

We can also see the help of the super keyword.

Help on class super in module _ builtin __:
Class super (object)
| Super (type)-> unbound super object
| Super (type, obj)-> bound super object; requires isinstance (obj, type)
| Super (type, type2)-> bound super object; requires issubclass (type2, type)
| Typical use to call a cooperative superclass method:
| Class C (B ):
| Def meth (self, arg ):
| Super (C, self). meth (arg)
|
| Methods defined here:
.......

As can be seen from the above, super is a class and is in the _ builtin _ module.

As described above, super is mainly used to call methods of the parent class.

The method before 2.2 can also be called. Why do we have to use super?

This is because super can block Multiple calls to the parent class method.

Super, changed the search order of the parent class. A special parent class object is returned.
Example:

Class A: pass class B (A): pass class C (A): pass class D (B, C): pass

This is the basic relationship between the four classes.

If super is not used, the D object will call this method twice to call the method in.

I hope this article will help you with Python programming.

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.