Python 基础继承

标签 python inheritance overriding

<分区>

我在理解 Python 中的继承时遇到了困难,但由于我在 Java 方面的经验比较丰富,所以我知道它是如何工作的……明确地说,我在这里搜索了问题以及在线文档,所以我知道这将立即被标记为重复问题 :P

我在 Codecademy 上的代码是这样通过的:

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

    def display_car(self):
        return "This is a %s %s with %s MPG." % (self.color, self.model, self.mpg)

    def drive_car(self):
        self.condition = "used"

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

但据我所知,我几乎是在定义一个新类……其中的继承在哪里?我可以做类似的事情吗:

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

也许有关键字

super

?

最佳答案

您可以调用 Car init 方法并传递其参数

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

或者您也可以使用 super 方法,这是评论中提到的首选方法。

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

关于Python 基础继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29170586/

相关文章:

objective-c - Objective-C - 反射和覆盖方法?

constructor - Swift:使用指定的初始化程序覆盖便利

python - conda 更新 : installation progress (version 4. 3)

c++ - 为什么具有私有(private)构造函数的类不阻止从此类继承?如何控制哪些类可以从某个基类继承?

c++ - "Ambiguous resolution"选择性构造函数继承错误

JavaFX 在 EventHandler 中使用父类(super class)

java - 从接口(interface)覆盖通用返回类型

python - 如何将日期信息附加到 read_csv 上的时间列

python - 计算列表中整数的最优雅方法

python - 如何更改 Pygame 窗口的名称?