首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何从子类调用基类的__init__方法?

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

Stack Overflow用户
提问于 2013-10-06 14:01:06
回答 1查看 183.4K关注 0票数 129

如果我有一个python类,比如:

代码语言:javascript
复制
class BaseClass(object):
#code and the init function of the base class

然后我定义一个子类,如下所示:

代码语言:javascript
复制
class ChildClass(BaseClass):
#here I want to call the init function of the base class

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

我写的代码是:

代码语言:javascript
复制
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)

我哪里错了?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-10-06 14:06:47

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

代码语言:javascript
复制
class BaseClass(object):
    def __init__(self, *args, **kwargs):
        pass

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

缩进不正确,以下是修改后的代码:

代码语言:javascript
复制
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__

下面是输出:

代码语言:javascript
复制
{'color': 'golden', 'mpg': 10, 'model': 'ford', 'battery_type': 'battery'}
票数 146
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19205916

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档