Python类继承没有做我认为应该做的事情

2024-05-23 21:07:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我想我理解python中的类继承,基本上你可以继承子类上父类的属性,以便重用,也可以“添加”到子类中,从而生成更复杂的类。你知道吗

我的问题是:下面有一个Car类,它以(model, color, mpg)作为参数,然后我创建了一个名为ElectricCar的新子类,它从父类Car继承…现在当我用(battery_type, model, color, mpg)调用ElectricCar时,我得到以下错误:

TypeError: init() takes exactly 2 arguments (5 given)

我知道你得把它修好。我需要将self.modelself.colorself.mpg添加到ElectricCar类中。但我为什么要这么做?如果我需要在子类上重新定义,那么这似乎违背了继承的目的。你知道吗

class Car(object):
    condition = "new"
    def __init__(self, model, color, mpg):
        self.model = model
        self.color = color
        self.mpg   = mpg

my_car = Car("DeLorean", "silver", 88)

class ElectricCar(Car):
    def __init__(self,battery_type):
        self.battery_type = battery_type

my_car = ElectricCar("molten salt", "Honda","black", "33")

Tags: selfmodelinitmydeftypecar子类
3条回答

I need to add self.model, self.color and self.mpg to the ElectricCar class.

Python允许您调用已替换的父类的方法。只需显式调用父类的构造函数。你知道吗

ElectricCar.__init__的第一个参数是电池类型。将其余位置参数存储在列表(args)中,并将它们解压到父构造函数:

class ElectricCar(Car):
    def __init__(self, battery_type, *args):
        super(ElectricCar, self).__init__(*args) # super().__init__(*args) in Py3k+
        self.battery_type = battery_type

当您定义__init__方法时,您将重写父类的__init__方法。这种重写就是创建super()函数的原因。你知道吗

你需要通过型号,颜色,每加仑在你的电动车类。然后可以调用super来初始化基类。你知道吗

class Car(object):
    condition = "new"
    def __init__(self, model, color, mpg):
        self.model = model
        self.color = color
        self.mpg   = mpg
        print model
        print color
        print  mpg

my_car = Car("DeLorean", "silver", 88)
print

class ElectricCar(Car):
    def __init__(self,battery_type, model, color, mpg):
        self.battery_type = battery_type
        print battery_type
        super(ElectricCar,self).__init__( model, color, mpg)

my_car = ElectricCar("molten salt", "Honda","black", "33")

相关问题 更多 >