子类参数初始化
我想问一下,当我们用一个父类来定义一个子类时,为什么还需要在父类的__init__
方法里初始化参数。我对JAVA的面向对象编程比较熟悉,记得在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")
我想问的是,为什么在ElectricCar类里写self.battery_type = battery_type
就足够了,这样的继承方式不应该可以吗?
2 个回答
3
你可以这样写:
class ElectricCar(Car):
def __init__(self, model, color, mpg, battery_type):
super(ElectricCar, self).__init__(model, color, mpg)
self.battery_type = battery_type
8
你可以通过使用 super()
这个代理对象 来调用被重写的 __init__
方法:
class ElectricCar(Car):
def __init__(self, model, color, mpg, battery_type):
super(ElectricCar, self).__init__(model, color, mpg)
self.battery_type = battery_type
如果你使用的是 Python 3,可以省略类名和 self 的引用:
class ElectricCar(Car):
def __init__(self, model, color, mpg, battery_type):
super().__init__(model, color, mpg)
self.battery_type = battery_type
无论哪种方式,调用 super()
都会给你一个代理对象,这个对象可以让你查看所有父类的属性和方法;它会找到下一个 __init__
方法,然后把它绑定,这样你就可以像调用普通方法一样去调用它。