[PYTHON] Make clear about super ()

Overview

I've been re-examining super (), which inherits python classes, every time a super class appears, so I'll try to clarify how to use it.

Use

What is super ()?

Used for inheriting the parent class

class Parent():
    def __init__(self, plus):
        self.min = 20
        self.plus = plus
    
    def plus(self):
        age = self.min + self.plus
        return age

class Child(Parent):
    def __init__(self):
        self.plus = 8

Even if you do (). Plus () in this state, __init__ of class Parent will be overwritten (self.min disappears), so an error will occur.

Therefore, if you do the following, it is a reason to inherit the __init __ of the parent class.

class Parent():
    def __init__(self, plus):
        self.min = 20
        self.plus = plus
    
    def plus(self):
        age = self.min + self.plus
        return age

class Child(Parent):
    def __init__(self):
        super().__init__(plus)
        self.plus = 8

The value of self.min is inherited and can output the value of 28

Is it __init__ aftersuper ()?

After super (), it doesn't have to be __init__, it just needs to be a method of the parent class.

class Parent():
    def message(self, text):
        print('your name is: {}'.format(text))

class Child(Parent):
    def message(self):
        print('your friend is: {}'.format(text))
        super().message(text)    

grammar

About the arguments in super ()

Different between python2 series and 3 series

The above seems to be standard

About the arguments in __init__ ()

Described in the comment in the previous example

class Parent():
    def __init__(self, plus):
        self.min = 20
        self.plus = plus
    
    def plus(self):
        age = self.min + self.plus
        return age

class Child(Parent):
    #self and super()Init()Arguments used in are described, and arguments can be added.
    def __init__(self, plus):
        # init()Self can be omitted in the inside, default variables can also be omitted*, Align the number of arguments with the init of the parent class
        super().__init__(plus)
        self.plus = 8

That is, regarding the child class

that's all

Recommended Posts

Make clear about super ()
[Super Basics] About jupyter Notebook
About Linux commands Super basic edition
Make GUI apps super easy with tkinter