Do I need to pass attributes from superclass's “__init__” to subclass's “__init__” manually, even if I use “super()”?
在下面的示例中(摘自python crash course book),为什么要将
1 2 3 4 5 6 7 8 9 | class Car(): def __init__(self, make, model, year): self.make = make self.model = model self.year = year class ElectricCar(Car): def __init__(self, make, model, year): super().__init__(make, model, year) |
why do we pass make, model and year to the subclass init method?
不然它会怎么把它们传给它的超类呢?
Isn't super() supposed to already transfer those parameters to the subclass's init method automatically?
不。
注意,在这个例子中,
1 2 3 4 5 6 7 8 9 10 | class Parent(): def __init__(self, foo): self.foo = foo class Child(Parent): def __init__(self, foo): super().__init__(foo) # doing something more... self.bar = 42 |
虽然您的措辞不太正确(这些参数实际上是从子类传递到超类的),但答案是"是",您需要手动为
在您的示例中,这似乎是不必要的,但您在
1 2 3 4 | class ElectricCar(Car): def __init__(self, make, model, year): super().__init__(make, model, year) self.battery = Battery() |
这就需要重新定义你的子类
注意,对于不可变的超类,您不需要传递任何参数:
1 2 3 4 | class Foo(int): def __init__(self, value): self.value = value super().__init__() |
它只接受你在