接上篇:【Python篇】Python 类和对象:详细讲解(上篇)
在编程中,类和对象是面向对象编程(OOP)的核心概念。Python 是一门支持面向对象编程的语言,这意味着你可以使用类和对象来组织代码,使其更加模块化、可维护和可扩展。
方法重写是在子类中定义与父类中同名的方法,以覆盖或扩展父类的行为。通过方法重写,子类可以改变或定制从父类继承的方法的功能。
在继承中,子类会继承父类的所有方法和属性。然而,有时你可能希望子类的某些方法与父类的方法表现不同。这时,你就可以在子类中重写这些方法。
我们来定义一个基本的 Car
类,然后在子类 ElectricCar
中重写它的方法。
class Car:
def __init__(self, brand, color):
self.brand = brand
self.color = color
self.speed = 0
def start(self):
self.speed = 10
print(f"The {self.color} {self.brand} car is starting at {self.speed} km/h.")
def stop(self):
self.speed = 0
print(f"The {self.color} {self.brand} car is stopping.")
# 定义一个 ElectricCar 类,继承自 Car 类
class ElectricCar(Car):
def __init__(self, brand, color, battery_capacity):
super().__init__(brand, color) # 调用父类的构造函数初始化 brand 和 color
self.battery_capacity = battery_capacity
def start(self):
# 重写 start 方法,让电动汽车以不同的方式启动
self.speed = 20 # 电动汽车启动时速度更快
print(f"The {self.color} {self.brand} electric car is silently starting at {self.speed} km/h with {self.battery_capacity} kWh capacity.")
def charge(self):
print(f"The {self.color} {self.brand} electric car is charging with {self.battery_capacity} kWh capacity.")
# 创建 ElectricCar 对象并使用它
electric_car = ElectricCar("Tesla", "White", 85)
electric_car.start() # 输出: The White Tesla electric car is silently starting at 20 km/h with 85 kWh capacity.
electric_car.stop() # 输出: The White Tesla car is stopping.
electric_car.charge() # 输出: The White Tesla electric car is charging with 85 kWh capacity.
Car
的方法:Car
类定义了 start
和 stop
方法。start
方法设置初始速度为 10 km/h,stop
方法将速度设为 0。ElectricCar
的方法重写: ElectricCar
继承了 Car
的所有属性和方法。ElectricCar
重写了 start
方法,使其启动速度为 20 km/h,并增加了电池容量的输出。super().__init__(brand, color)
调用了父类的构造函数,以确保 brand
和 color
属性被正确初始化。多继承是指一个类可以同时继承多个父类的特性。Python 支持多继承,但使用时需要注意可能的复杂性,尤其是在多个父类中有相同方法的情况下。
多继承允许一个子类同时从多个父类中继承方法和属性。这种特性非常强大,但也可能带来复杂的依赖关系。
创建两个父类 Vehicle
和 Electric
,然后定义一个子类 ElectricCar
,它同时继承自这两个父类。
class Vehicle:
def __init__(self, brand):
self.brand = brand
def start(self):
print(f"The {self.brand} vehicle is starting.")
class Electric:
def __init__(self, battery_capacity):
self.battery_capacity = battery_capacity
def charge(self):
print(f"Charging with {self.battery_capacity} kWh battery capacity.")
# ElectricCar 继承了 Vehicle 和 Electric
class ElectricCar(Vehicle, Electric):
def __init__(self, brand, color, battery_capacity):
Vehicle.__init__(self, brand) # 初始化 Vehicle 类的属性
Electric.__init__(self, battery_capacity) # 初始化 Electric 类的属性
self.color = color
def start(self):
print(f"The {self.color} {self.brand} electric car is silently starting with {self.battery_capacity} kWh battery.")
# 使用 ElectricCar 类
electric_car = ElectricCar("Tesla", "White", 85)
electric_car.start() # 输出: The White Tesla electric car is silently starting with 85 kWh battery.
electric_car.charge() # 输出: Charging with 85 kWh battery capacity.
Vehicle
和 Electric
父类:这两个类分别提供 brand
和 battery_capacity
属性,并各自定义了 start
和 charge
方法。ElectricCar
的多继承: ElectricCar
同时继承了 Vehicle
和 Electric
的属性和方法。__init__
方法中分别调用 Vehicle.__init__(self, brand)
和 Electric.__init__(self, battery_capacity)
来初始化父类的属性。ElectricCar
中的 start
方法重写了 Vehicle
类的 start
方法,以自定义启动行为。当使用多继承时,Python 会根据方法解析顺序(MRO)来决定调用哪个父类的方法。MRO 是 Python 确定方法调用顺序的规则。
查看 MRO:
ClassName.mro()
方法查看一个类的 MRO。例如:
print(ElectricCar.mro())
这将输出:
[<class '__main__.ElectricCar'>, <class '__main__.Vehicle'>, <class '__main__.Electric'>, <class 'object'>]
MRO 解析顺序:Python 会从左到右、从上到下地查找方法。在本例中,ElectricCar
先查找自身,然后是 Vehicle
,接着是 Electric
,最后是 Python 所有类的基类 object
。
类的组合是指一个类可以包含其他类的实例作为属性,从而创建更复杂的对象。与继承相比,组合更灵活,因为它不涉及继承链的复杂性。
类的组合通过在一个类中包含另一个类的实例,来实现功能模块化。这种方法使得类的职责更加明确,也让代码更加易于维护。
让我们定义一个 Battery
类,并将其组合到 ElectricCar
中。
class Battery:
def __init__(self, capacity):
self.capacity = capacity
def charge(self):
print(f"Charging the battery with {self.capacity} kWh capacity.")
class ElectricCar:
def __init__(self, brand, color, battery_capacity):
self.brand = brand
self.color = color
self.battery = Battery(battery_capacity) # 组合 Battery 类
def start(self):
print(f"The {self.color} {self.brand} electric car is starting.")
def charge(self):
self.battery.charge() # 调用 Battery 类的 charge 方法
# 使用 ElectricCar 类
electric_car = ElectricCar("Tesla", "White", 85)
electric_car.start() # 输出: The White Tesla electric car is starting.
electric_car.charge() # 输出: Charging the battery with 85 kWh capacity.
Battery
类代表电动汽车的电池。它有一个 charge
方法来模拟充电。ElectricCar
类拥有一个 Battery
类的实例,作为其 battery
属性。electric_car.charge()
时,实际是调用 Battery
类的 charge
方法。ElectricCar
是一个 Car
。ElectricCar
有一个 Battery
。组合通常比继承更灵活,因为你可以在不改变类继承层次的情况下,动态地更改组合类的行为。
在本次学习中,你已经掌握了以下关键概念:
在多继承中,方法解析顺序(MRO)是 Python 用来确定类层次结构中的方法调用顺序的机制。理解 MRO 对于有效使用多继承和调试复杂的类层次结构非常重要。
MRO 决定了当你调用一个方法时,Python 如何查找该方法的定义。MRO 是通过一种称为 C3 线性化的算法来计算的,该算法确保了类层次结构中的一致性和方法解析的确定性。
你可以使用类的 mro()
方法或 __mro__
属性来查看一个类的 MRO。
例如:
class A:
pass
class B(A):
pass
class C(A):
pass
class D(B, C):
pass
print(D.mro())
输出将显示 D
类的 MRO:
[<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>]
当类层次结构变得复杂时,MRO 可以帮助你理解方法调用的顺序。例如,如果 D
类继承了 B
和 C
,而 B
和 C
又都继承自 A
,MRO 可以告诉你调用 D
的方法时,Python 是如何在 B
、C
和 A
之间选择方法的。
通过了解 MRO,你可以避免潜在的方法冲突,并确保你的代码在多继承情况下能够按照预期工作。
在面向对象编程中,抽象类和接口用于定义类的框架和通用行为,确保子类实现这些行为。
抽象类是一种不能被实例化的类,它通常用于定义子类必须实现的方法。抽象类提供了一个模板,让你可以确保所有子类都具有某些共同的行为。
在 Python 中,你可以使用 abc
模块中的 ABC
和 abstractmethod
来定义抽象类和抽象方法。
例如:
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
pass
class Dog(Animal):
def sound(self):
return "Woof!"
class Cat(Animal):
def sound(self):
return "Meow!"
在这个例子中,Animal
是一个抽象类,它定义了一个抽象方法 sound
。任何继承 Animal
的子类都必须实现 sound
方法,否则会引发错误。
以上就是关于【Python篇】Python 类和对象:详细讲解(中篇)的内容啦,各位大佬有什么问题欢迎在评论区指正,您的支持是我创作的最大动力!❤️