在 python 中使用父 class 的魔术方法 __init__ 初始化子 class

Initializing a child class with the magic method __init__ of the parent class in python

我一直在使用 python 进行在线课程。一节课好像从a,b,c到z.

在最近的课程中,在子 class 的初始化部分中,它似乎采用父 class 数组并将其传递给子 [=26= 的新魔术方法初始化参数].

class ChildClass(ParentClass):
    def __init__(self, speed, direction):
        ParentClass.__init__(self, [speed, direction])

我在网络上找不到任何资源来证实我的解释。

即使未向 self.speed 和 self.direction 分配任何内容,父级是否传递其参数?

子 class ChildClass__init__ 方法正在将其参数传递给其父 class ParentClass__init__ 方法, 然后父 __init__ 方法继续对象初始化。假设 ChildClass.__init__ 仅包含显示的代码,子方法的唯一要点是使子构造函数的签名不同于父构造函数的签名;如果 ChildClass.__init__ 被删除,所有对 ChildClass(speed, direction) 的调用只需要更改为 ChildClass([speed, direction]) 以继续做同样的事情。

parent class 就像制造一辆有 4 个轮子的汽车 class。

car:
    def__init__(self, wheels):
        self.wheels = 4    

您可以在 init 函数中或下面的 self 中定义轮子的数量,但是在 init 中,任何 wheels = x 都需要放在最后。

def__init__(self, wheels = 4, color):   # this would fail
def__init__(self, color, wheels = 4): # this would work

现在我们创造一辆雪佛兰(因为福特很烂)

chevy(car):
    def__init__(self, wheels, color = blue):
        self.color = color

    super().__init__(wheels) 

super 来自 parent class,parent class 中的任何内容都需要在 child class 中,(如果没有轮子,它就不再是汽车了)这会使它坠毁。