python3多继承初始化调用方法,python3广度优先,python2是深度优先
当我们讨论多继承时,一个类可以从多个父类继承属性和方法。在Python中,使用super()
可以帮助我们处理复杂的多继承情况,确保每个父类的初始化方法都被正确调用。
下面是一个使用多继承的例子,其中Vehicle
类作为基类,而ElectricVehicle
和SportsCar
作为中间层的父类。最终ElectricSportsCar
类将从这两个中间父类继承,并使用super()
来调用它们的初始化方法。
示例代码
class Vehicle:
def __init__(self, name, color):
self.name = name
self.color = color
print(f"Initialized {self.name} as a {self.color} vehicle.")
class ElectricVehicle(Vehicle):
def __init__(self, name, color, battery_capacity):
super().__init__(name, color) # 调用Vehicle的初始化方法
self.battery_capacity = battery_capacity
print(f"Initialized {self.name} as an electric vehicle with a {self.battery_capacity} kWh battery.")
class SportsCar(Vehicle):
def __init__(self, name, color, top_speed):
super().__init__(name, color) # 调用Vehicle的初始化方法
self.top_speed = top_speed
print(f"Initialized {self.name} as a sports car with a top speed of {self.top_speed} km/h.")
class ElectricSportsCar(ElectricVehicle, SportsCar):
def __init__(self, name, color, battery_capacity, top_speed):
super(ElectricSportsCar, self).__init__(name, color, battery_capacity) # 调用ElectricVehicle的初始化方法
super(SportsCar, self).__init__(name, color, top_speed) # 调用SportsCar的初始化方法
print(f"Initialized {self.name} as an electric sports car with a {self.battery_capacity} kWh battery and a top speed of {self.top_speed} km/h.")
# 创建一个ElectricSportsCar实例
my_electric_sports_car = ElectricSportsCar("Tesla Roadster", "Red", 200, 400)
解释
- Vehicle 类 - 基础类,定义了所有车辆共有的属性和方法。
- ElectricVehicle 类 - 继承自
Vehicle
类,添加了电池容量属性。 - SportsCar 类 - 同样继承自
Vehicle
类,添加了最高时速属性。 - ElectricSportsCar 类 - 继承自
ElectricVehicle
和SportsCar
类,结合了两者的特性。
在ElectricSportsCar
类中,我们需要明确地调用每个父类的初始化方法,因为Python 3在多继承情况下不再自动调用所有父类的初始化方法。这里我们分别调用了ElectricVehicle
和SportsCar
的初始化方法。
输出
运行上述代码会得到以下输出:
Initialized Tesla Roadster as a Red vehicle.
Initialized Tesla Roadster as an electric vehicle with a 200 kWh battery.
Initialized Tesla Roadster as a sports car with a top speed of 400 km/h.
Initialized Tesla Roadster as an electric sports car with a 200 kWh battery and a top speed of 400 km/h.
这段输出表明每个父类的初始化方法都已经被正确调用。