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

Prakhar Mohan Srivastava:

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

我要去哪里错了?

Mingyu :

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在基类__init__的子类__init__之后调用基类方法吗?

从子类调用基类的扩展方法

如何从子类中调用重写的父类方法?

从子类调用基类

Java如何从子类中调用方法

如何确保某些方法从子类(Java)中的方法从抽象超类中调用

如何从子类对象列表中的基类继承

Python-如何从子类实例调用超类的方法?

为什么从子类的超类调用方法中获得“ this”?

Django / Python:如何从子类中的父类调用函数?

在Python中动态创建类后如何调用父类的__init__方法?

如何在javascript中从子类调用父方法?

如何在不同类 __init__ 中的实例上调用类方法

从子类嵌套类访问基类方法

子类和方法-如何从子类调用方法?

抽象类错误“未从基类调用__init__方法”

从子类增强基类方法的最佳方法是什么

从派生类自动调用基类 __init__

在C#中,如何从子类访问基类变量值

在python中可以编写一个将在子类的__init__之后自动调用的方法

Java-父类正在从子类中调用方法?

使用python中父类的魔术方法__init__初始化子类

如何在Flutter中从子类函数调用父类函数

从子类调用超类函数的正确方法

从子类组件调用父类组件的方法

具有从子类JS调用的方法的类范围

PySide.QtGui RuntimeError:对象的基类的'__init__'方法未调用...但是它是

在python中从子类调用父类构造函数

在php中从子类到父类调用函数