The other day I learned about 100 Days Of Code, which was popular on Twitter for a while. The purpose of this article is to keep a record and output how much I, as a beginner, can grow through 100 days of study. I think there are many mistakes and difficult to read. I would appreciate it if you could point out!
--Progress: Pages 69-73 --Chapter 3: Classes and Inheritance ――I will write down what I often forget or didn't know about what I learned today.
How to initialize a parent class from a child class
--Initialization using the __init__
method
__init__
method#Parent class
class MyBaseClass(object):
def __init__(self, value):
self.value = value
#Child class
class MyChildClass(MyBaseClass):
def __init__(self):
MyBaseClass.__init__(self, 5) #Of the parent class__init__Call and initialize the method
__init__
methodThis method works fine in simple hierarchies, but multiple inheritance can cause strange behavior if you call the superclass's __init__
method directly under the influence. Especially when inheriting diamonds, it causes unexpected behavior.
Diamond inheritance means that a subclass inherits from two separate classes, and the two have the same superclass in the inheritance refurbishment. For example, define two child classes that inherit from MyBaseClass and a child class that inherits them as follows:
#Parent class
class MyBaseClass(object):
def __init__(self, value):
self.value = value
#Child class 1 that inherits the parent class
class TimesFive(MyBaseClass):
def __init__(self, value):
MyBaseClass.__init__(self, value)
self.value *= 5
#Child class 2 that inherits the parent class
class PlusTwo(MyBaseClass):
def __init__(self, value):
MyBaseClass.__init__(self, value)
self.value += 2
#Define a child class that inherits the two classes and make MyBaseClass the apex of the diamond
class ThisWay(TimesFive, PlusTwo):
def __init__(self, value):
TimesFive.__init__(self, value)
PlusTwo.__init__(self, value)
foo = ThisWay(5)
print('Should be ( 5 * 5) + 2 = 27 but is', foo.value)
Output result
Should be ( 5 * 5) + 2 = 27 but is 7
The output should be 27, but this Way's argument 5 should be multiplied by 5 with TimesFive, plus 2 with PlusTwo, and now it's 7. This is because the call to PlusTwo.init resets to 5 when MyBaseClass.init is called a second time. In Python3 you can solve this problem by using super. Also, ** Python 3 should always use super. ** **
class Explicit(MyBaseClass):
def __init__(self, value):
super(__class__, self).__init__(value * 2)
class Implicit(MyBaseClass):
def __init__(self, value):
super().__init__(value * 2)
print('Explicit', Explicit(10).value)
print('Implicit', Implicit(10).value)
Output result
Explicit 20
Implicit 20
--Python standard method resolution order solves superclass initialization order and diamond inheritance problems --Always use the built-in function super to initialize the parent class
Recommended Posts