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.
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
__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)
super ()
Different between python2 series and 3 series
__python2 series __
super (parent class name, self). Parent class method
__python3 series __
super (). Parent class method
The above seems to be standard
__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
The argument of def __init __ (argument)
is
Describe self
Describe the arguments used in init () of super ()
Arguments can be added
The argument of super () .__ init__ (argument)
is
Do not write self
Align the number of arguments with the init of the parent class
Default variable is optional
that's all