子类初始化参数

Alk*_*ian 2 python inheritance class

我想问一下,如果我们使用基类定义子类,为什么我们需要在__init__方法中初始化父类中的参数.我和JAVA OOP类似,我记得在Java中我们只是在子类中添加新参数.

如果我对Java也是错的,有人可以解释一下这样做的原因吗?是不是继承应该让我们的生活更容易编程.

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

    def display_car(self):
        print "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



my_car = ElectricCar("Auris", "golden", 89, "molten salt")
Run Code Online (Sandbox Code Playgroud)

我的意思是为什么self.battery_type = battery_type内部的ElectricCar类不足以进行这种继承?

Mar*_*ers 5

您可以__init__使用super()代理对象调用重写的方法:

class ElectricCar(Car):
    def __init__(self, model, color, mpg, battery_type):
        super(ElectricCar, self).__init__(model, color, mpg)
        self.battery_type = battery_type
Run Code Online (Sandbox Code Playgroud)

如果您使用的是Python 3,则可以省略类和自引用:

class ElectricCar(Car):
    def __init__(self, model, color, mpg, battery_type):
        super().__init__(model, color, mpg)
        self.battery_type = battery_type
Run Code Online (Sandbox Code Playgroud)

无论哪种方式,super()调用都会为您提供一个代理对象,您可以在其上查找整个父类链的属性和方法; 它会找到__init__链中的下一个方法,然后将其绑定,以便您可以将其称为常规方法.