如何从子类调用基类的 __init__ 方法? [英] How to call Base Class's __init__ method from the child class?

查看:37
本文介绍了如何从子类调用基类的 __init__ 方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个 python 类:

If I have a python class as:

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

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

And then I define a child class such as:

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

如果基类的 init 函数接受一些参数,我将它们作为子类的 init 函数的参数,我该如何将这些参数传递给基类?

If the init function of the base class takes some arguments that I am taking them as arguments of the child class's init function, how do I pass these arguments to the base class?

我写的代码是:

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)

您的缩进不正确,这是修改后的代码:

Your indentation is incorrect, here's the modified code:

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'}

这篇关于如何从子类调用基类的 __init__ 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆