父类名 . __init__(self, ...)
可以将父类中的init中的属性重复调用,减少代码的重复
class Vehicle: def __init__(self, name, speed, load, power): self.name = name self.speed = speed self.load = load self.power = power def run(self): print('%s我开动啦'%self.name) class Subway(Vehicle): def __init__(self,name, speed, load, power,line): Vehicle.__init__(self, name, speed, load, power) self.line = line def show_info(self): print(self.name, self.line) line1 = Subway('郑州地铁', '30m/s','500','电', '1号') line1.show_info() #调用自身的方法 line1.run() #调用父类中的类方法
父类名 . 函数名(self)
子类中调用父类中类方法的逻辑
class Vehicle: def __init__(self, name, speed, load, power): self.name = name self.speed = speed self.load = load self.power = power def run(self): print('%s我开动啦'%self.name) class Subway(Vehicle): def __init__(self,name, speed, load, power,line): Vehicle.__init__(self, name, speed, load, power) self.line = line def show_info(self): print(self.name, self.line) def run(self): Vehicle.run(self) #加上这句,可以实现同名函数,调用父类中的逻辑 print('%s我来自子类'%self.line) line1 = Subway('郑州地铁', '30m/s','500','电', '1号线') line1.show_info() #调用自身的方法 line1.run()
super 方法
调用父类逻辑时,不用担心类名的变动
class Vehicle: def __init__(self, name, speed, load, power): self.name = name self.speed = speed self.load = load self.power = power def run(self): print('%s我开动啦'%self.name) class Subway(Vehicle): def __init__(self,name, speed, load, power,line): # Vehicle.__init__(self, name, speed, load, power) super().__init__(name, speed, load, power) #super 方法,这样就不用担心类名被修改 self.line = line def show_info(self): print(self.name, self.line) def run(self): # Vehicle.run(self) #加上这句,可以实现同名函数,调用父类中的逻辑 super().run() #效果和上面代码一样,更适合 print('%s我来自子类'%self.line) line1 = Subway('郑州地铁', '30m/s','500','电', '1号线') line1.show_info() #调用自身的方法 line1.run() #调用父类中的类方法
super().__init__(name, speed, load, power) 等同于:
super(Subway, self).__init__(name, speed, load, power)