1 class Vehicle: 2 country = 'china' 3 4 def __init__(self, name, speed, load, power): 5 self.name = name 6 self.speed = speed 7 self.load = load 8 self.power = power 9 10 def run(self): 11 print('开动了') 12 13 14 class Subway(Vehicle): 15 def __init__(self, name, speed, load, power, line): 16 # Vehicle.__init__(self, name, speed, load, power) # 为什么要传self,是因为类里面只有实例化的过程和实例调用类方法才会自动传入self 17 super().__init__(name, speed, load, power) # 用此方法就不需要写父类的类名且不用手动传递self 18 # self.name = name 19 # self.speed = speed 20 # self.load = load 21 # self.power = power 22 self.line = line 23 24 def show_info(self): # 派生的方法 25 print(self.name, self.line) 26 27 def run(self): # 定义一个新的方法,相当于重写了父类的此方法 28 # Vehicle.run(self) # 可以加上父类的方法 29 super().run() # 不用再手动传递self 30 print('%s %s开动了' % (self.name, self.line)) 31 32 33 line13 = Subway('北京地铁', '10km/s', 10000, '电力', 13) 34 print(line13.speed) 35 print(line13.load) 36 line13.show_info() 37 line13.run() 38 输出: 39 10km/s 40 10000 41 北京地铁 13 42 开动了 43 北京地铁 13开动了
不用写父类名,不用传递self参数