SoFunction
Updated on 2024-11-17

super in python

raise (a subject)superThe most straightforward idea is that it represents the parent class and performs certain methods for it. But that's about as far as it goes, so here's an overview of thesuper Further understanding

The full form of super

commonsuper The usage is as follows

class Person():
    def __init__(self,name):
         = name
        print('Person')

class Male(Person):
    def __init__(self,age):
        super().__init__('xiaoming')
         = age
        print("Male")

m = Male(12)
print(m.__dict__)

The result of the above implementation is

在这里插入图片描述

This result is also consistent with the understanding thatMale inheritedPerson, which executes the initialization method of the parent class at initialization time, and thus inherits the name attribute of the parent class.

But really.super The full form of the

super(Male, self).__init__('xiaoming')

super anresembleThe second argument is a class or object, which determines what mro to use, and the first argument is a class, which determines which class after the mro to start looking for, and binds the function to the second argument. Both arguments are optional.

In this example.self just likeMale instance object, so theself The mro is [Male,Person,Object], and the first argument isMaleThe first step in the process is to use theMale backPersonDiscoverPerson there are__init__ function, so it just executes thePerson (used form a nominal expression)__init__ function, which is thesuper The statement on the line is equivalent to the

# super(Male, self).__init__('xiaoming')
Person.__init__(self,'xiaoming')

Implementation results as above

在这里插入图片描述

Use of super

super Can be used outside of the defining class

class Animal():
    def __init__(self,name):
         = name

class Person(Animal):
    def __init__(self,name,age):
        super().__init__(name)
         = age
        print('Person')

class Male(Person):
    def __init__(self,name,age):
        super(Person,self).__init__(name,age)
        print("Male")

m = Male('xiaoming',12)
super(Male,m).__init__('xiaoming',12)
print(m.__dict__)

The result of the execution is

在这里插入图片描述

You can see that line 16 reported an error, the reason for the error is that this time theself Represented byMale Instance.Male The mro isMalePersonAnimalObjectMale At the time of instantiation the parent class's__init__ method, and at this point thesuper The first parameter of thePersonThe program is then used toPerson backAnimalbut (not)Animal (used form a nominal expression)__init__ method has only one parameter.super Instead, 2 parameters were passed and an error was reported. Correctly changed to

# class Person:
super(Person,self).__init__(name)

The result of the execution is

在这里插入图片描述

can be seenMale The instantiation bypasses thePersonThe only thing that is output is theAnimal cap (a poem)Male. And the execution of thesuperThe execution of theMale of the parent class (Person, Animal) of the__init__ Methodology. 2 points are explained:

  1. super The first parameter of the parameter determines the choice ofself The class after which class is the mro of which class.
  2. super can be executed outside of the class definition.

Another example will make it clearer

在这里插入图片描述

Intuitively.D instance of the parent class executes thesay() The first thing you'll find is theBThe program will then execute theB of the parent class of thesay()and will then output'A'. It turned out to be'C'The reason for this is thatself representD instances, and theD The mro is['B','C','A']D instance of the parent class executes thesay() You'll find it.B fulfillmentB (used form a nominal expression)super method, which is equivalent to thesuper(B,self).say()And at this point in timeself in the name ofDThe mro search will selectB The class that follows is also known asCImplementationC (used form a nominal expression)say()The final result is then output'C'

Classes that use thesuper can be omitted and written directly assuper()The super takes the class as its first argument and the first argument of the function as its second argument.. Obviously, omitting the parameters in this waysuper Cannot be used directly outside of a class.

Finally, checking the mro of a class can be done with theclass.__mro__ or() gain

在这里插入图片描述

To this point this article on python super in the article is introduced to this, more related python super content please search for my previous articles or continue to browse the following related articles I hope you will support me more in the future!