Introduction to Super () function in Python and usage sharing _python

Source: Internet
Author: User
Tags class definition inheritance instance method in python

First look at the definition of the super () function:

super([type [,object-or-type]])

Return a **proxy object** This delegates method calls to a **parent or sibling** class of type.

Returns a proxy object that is responsible for assigning a method call to a parent or sibling class of the first parameter to complete.

How is the parent or sibling class determined?

The __mro__ property of the first parameter determines the order of the search, and super refers to the next class in the MRO (method resolution order), not necessarily the parent class!

Super () and GetAttr () use the __mro__ property to resolve the search order, __mro__ is actually a read-only tuple.

What is the order of classes in MRO?

In fact, the MRO list itself is based on a C3 linearization process, which can be referenced here, with a simple description of the principle:

In MRO, the base class always appears after the derived class, and if there are multiple base classes, the relative order of the base classes does not change.

MRO is actually the result of the sequence traversal of the inheritance tree, a tree with a structure into a linear table, so along this list to go up, you can not iterate through the whole tree, but also solve the diamond problem of multiple inheritance.

For example:

Class Root:
  Pass

class A (root):
  Pass

class B (root):
  Pass

class C (A, B):
  Pass

Print ( c.__mro__)

# The output result is:
# (<class ' __main__. C ', <class ' __main__. A ', <class ' __main__. B ', <class ' __main__. Root ", <class ' object ' >)

Super () actually returns a Super object for the agent!

When you call the super () constructor, you simply return a super () object and do nothing else.

Then when you make a method call to the Super object, what happens is as follows:

Find the next class in the __mro__ list of the first argument that directly defines the method, and instantiate an object
Then bind the self variable of this object to the second argument, and return the object

As an example:

Class Root:
  def __init__ (self):
    print (' Root ')

class A (Root):
  def __init__ (self):
    super (). __init__ () # is equivalent to super (A, self). __init__ ()

In the construction method of a, call super () to get a Super object, and then call the Init method on the object, which is the Super object that searches the __mro__ list of a, finds the first class that defines the __init__ method, and then finds the root, Then call root.__init__ (self), where self is the second parameter of super (), the first parameter of the compiler that is automatically populated, that is, the __init__ of a, which completes the allocation of the __init__ method call.

Note: In the inheritance of many languages, subclasses must invoke the constructor method of the parent class to ensure that the object of the subclass can populate the properties of the parent class! Instead of initializing a parent class object ... (That's what I've always understood ...). Python is much better, called the parent-class construction method, is plainly to pass self to the parent class of the construction method, my little body bone is so to you, whatever you do to toss it: joy:

Parameter description

Super ()-> same as Super (__class__, <first argument>) # <first argument> refers to the first parameter of the function called Super
( Type)-> unbound Super Object
super (type, obj)-> bound Super object; requires Isinstance (obj, type)
super (t Ype, type2)-> bound Super object; Requires Issubclass (type2, type) typical use to call

 a cooperative superclass method:
  class C (B):
    def meth (SE LF, ARG):
      super (). Meth (ARG) This works for
  class methods too:
  class C (B):
    @classmethod
    def cmeth (CLS, ARG):
      super (). Cmeth (ARG)

If the second argument is supplied, the self of the parent object that is found is bound to this parameter, and the method of the object is invoked to automatically implicitly pass self.
If the second argument is an object, then Isinstance (obj, type) must be true. If the second argument is a type, then Issubclass (type2, type) must be true

If the second argument is not passed, then the object returned is unbound, and the method that calls the unbound object needs to pass the first argument manually, similar to base.__int__ (self, A, b).

Super () with no parameters can only be used in the class definition (because it relies on the second argument of caller), and the compiler automatically populates the parameters based on the currently defined class.
That is, when all subsequent methods that call Super return an object, the first argument self is the second parameter of super (). Because the so-called method in Python is a function with the first argument of self, the A.B () implicitly assigns a to the first parameter of B () when the method is invoked.

Two common uses of super ():

In single inheritance, super is used to refer to an implicit reference to the parent class, avoiding the direct use of the parent class's name
Multiple inheritance, solving diamond problems (TODO)

An object-oriented approach to understanding

In fact, I think the syntax in Python is easier to understand than the object-oriented nature, which is much easier to understand than implicitly passing this in Java.

A function is a piece of code that accepts input and returns output. The so-called method is that a function has an implicit pass parameter. So the method is a piece of code that is shared by all instances of the class, and the only difference is that each instance is invoked to pass this or self to the method.

What is the construction method? It's also an instance method, which can only be invoked after the object has been generated, so the argument for the __init__ method in Python is self. When you call a construction method, you have already allocated memory for the object, and the construction method only acts as an initialization, that is, to assign an initial value to the memory.

Java in the so-called static variable is actually a class variable, in fact, is also allocated to the class memory, where these variables, so the class object in Python I think is very reasonable, and more intuitive than Java. As for the static method, it has nothing to do with the object, the essence is an independent function, but it is written in the class. The Classmethod in Python is actually a static method, but it relies on the CLS object, the CLS being the class object, but as long as you want to use this method, the class object must exist, unlike the instance object, which requires manual instantiation. So Classmethod can also be considered as a static variable. And Staticmethod is the real static method, is a stand-alone function, does not depend on any object.

An instance method in Java must depend on the existence of an object because it is to be implicitly transmitted this is not implicit if the object does not exist. Therefore, there is no this pointer in the static method, and the instance method cannot be invoked. The instance method in Python can be invoked by the class name, only because self cannot implicitly pass it, so it must be passed explicitly.

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.