How to call Base Class's __init__ method from the child class?
本问题已经有最佳答案,请猛点这里访问。
如果我有一个python类:
1 2 | class BaseClass(object): #code and the init function of the base class |
然后我定义了一个子类,比如:
1 2 | class ChildClass(BaseClass): #here I want to call the init function of the base class |
如果基类的init函数接受一些参数,我将它们作为子类init函数的参数,那么如何将这些参数传递给基类?
我写的代码是:
1 2 3 4 5 6 7 8 9 10 11 12 | class Car(object): condition ="new" def __init__(self, model, color, mpg): self.model = model self.color = color self.mpg = mpg class ElectricCar(Car): def __init__(self, battery_type, model, color, mpg): self.battery_type=battery_type super(ElectricCar, self).__init__(model, color, mpg) |
我哪里出错了?
你可以用
1 2 3 4 5 6 7 | class BaseClass(object): def __init__(self, *args, **kwargs): pass class ChildClass(BaseClass): def __init__(self, *args, **kwargs): super(ChildClass, self).__init__(*args, **kwargs) |
您的缩进不正确,下面是修改后的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class Car(object): condition ="new" def __init__(self, model, color, mpg): self.model = model self.color = color self.mpg = mpg class ElectricCar(Car): def __init__(self, battery_type, model, color, mpg): self.battery_type=battery_type super(ElectricCar, self).__init__(model, color, mpg) car = ElectricCar('battery', 'ford', 'golden', 10) print car.__dict__ |
输出结果如下:
1 | {'color': 'golden', 'mpg': 10, 'model': 'ford', 'battery_type': 'battery'} |
正如明玉所指出的,在格式化方面有一个问题。除此之外,我强烈建议不要在调用
1 2 3 4 5 6 7 8 9 10 11 12 13 | class Car(object): condition ="new" def __init__(self, model, color, mpg): self.model = model self.color = color self.mpg = mpg class ElectricCar(Car): def __init__(self, battery_type, model, color, mpg): self.battery_type=battery_type super().__init__(model, color, mpg) |
多亏了欧文·迈尔指出了在超级()中使用
可以这样调用超级类的构造函数
1 2 3 4 5 6 7 8 9 | class A(object): def __init__(self, number): print"parent", number class B(A): def __init__(self): super(B, self).__init__(5) b = B() |
注:
只有父类继承
如果您使用的是python 3,建议只调用super()而不使用任何参数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class Car(object): condition ="new" def __init__(self, model, color, mpg): self.model = model self.color = color self.mpg = mpg class ElectricCar(Car): def __init__(self, battery_type, model, color, mpg): self.battery_type=battery_type super().__init__(model, color, mpg) car = ElectricCar('battery', 'ford', 'golden', 10) print car.__dict__ |
不要用类调用super,因为根据这个答案,它可能导致无限递归异常。