如何从子类调用基类的__init__方法?

如果我有一个Python类:

class BaseClass(object): #code and the init function of the base class 

然后我定义一个孩子类,如:

 class ChildClass(BaseClass): #here I want to call the init function of the base class 

如果基类的初始化函数需要一些参数,我将它们作为子类的初始化函数的参数,那么如何将这些parameter passing给基类呢?

我写的代码是:

 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) 

我哪里错了?

你可以使用super(ChildClass, self).__init__()

 class BaseClass(object): def __init__(self, *args, **kwargs): pass class ChildClass(BaseClass): def __init__(self, *args, **kwargs): super(ChildClass, self).__init__(*args, **kwargs) 

您的缩进不正确,下面是修改的代码:

 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__ 

这是输出:

 {'color': 'golden', 'mpg': 10, 'model': 'ford', 'battery_type': 'battery'} 

正如明宇指出,格式化存在问题。 除此之外,我强烈build议在调用super()不要使用Derived类的名称 ,因为它会使代码不灵活(代码维护和inheritance问题)。 在Python 3中,改为使用super().__init__ 。 以下是合并这些更改后的代码:

 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) 

感谢Erwin Mayer指出在使用__class__和super()

你可以像这样调用超类的构造函数

 class A(object): def __init__(self, number): print "parent", number class B(A): def __init__(self): super(B, self).__init__(5) b = B() 

注意:

这只会在父类inheritanceobject时才起作用

如果您使用的是Python 3,build议您只需调用super(),而不使用任何参数:

 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__ 

不要用class来调用超类,因为这可能导致无限的recursionexception。