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

时间:2013-10-06 06:01:06

标签: python python-2.7 inheritance constructor

如果我有一个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

如果基类的init函数接受一些我将它们作为子类的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(ElectricCar, self).__init__(model, color, mpg)

我哪里错了?

4 个答案:

答案 0 :(得分:102)

您可以使用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'}

答案 1 :(得分:28)

正如Mingyu指出的那样,格式化存在问题。除此之外,我强烈建议在调用super()时不使用Derived类的名称,因为它会使您的代码不灵活(代码维护和继承问题)。在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()

的问题

答案 2 :(得分:10)

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

class A(object):
    def __init__(self, number):
        print "parent", number

class B(A):
    def __init__(self):
        super(B, self).__init__(5)

b = B()

注意:

仅当父类继承object

时才会起作用

答案 3 :(得分:7)

如果您使用的是Python 3,建议您不要使用任何参数调用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__

请勿使用调用super,因为根据I am sharing my JSFiddle script, Kindly help me,它可能会导致无限递归异常。