gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 21:11:50 25 4
gpt4 key购买 nike

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

我哪里错了?

最佳答案

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

关于python - 如何从子类调用基类的 __init__ 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19205916/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com