136

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

4 回答 4

153

你可以使用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'}
于 2013-10-06T06:06:47.350 回答
64

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

于 2015-01-02T10:17:45.380 回答
14

如果您使用的是 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 ,因为根据这个答案可能会导致无限递归异常。

于 2016-02-12T07:36:52.693 回答
12

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

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

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

b = B()

笔记:

这仅在父类继承时才有效object

于 2013-10-06T06:06:11.247 回答