1 Python 2.7中的继承 2 在Python 2.7中,继承语法稍有不同,ElectricCar 类的定义类似于下面这样: 3 class Car(object): 4 def __init__(self, make, model, year): 5 --snip--
6
7 class ElectricCar(Car): 8 def __init__(self, make, model, year): 9 super(ElectricCar, self).__init__(make, model, year) 10 --snip--
11 函数super() 需要两个实参:子类名和对象self 。为帮助Python将父类和子类关联起来,这些实参必不可少。另外,在Python 2.7中使用继承时,务必在定义父类时在括号内指定object 。 12
13 Python 3中的继承 14 class Car(): 15 def __init__(self, make, model, year): 16 --snip--
17
18 class ElectricCar(Car): 19 def __init__(self, make, model, year): 20 '''初始化父类的属性'''
21 super().__init__(make, model, year) 22 --snip--