作者:还怪好嘞 发布时间:2026-05-30 难度:⭐⭐⭐⭐ 预计阅读时间:35分钟
前言
在上一篇中,我们学习了类与对象的基础知识。本篇将深入探讨Python面向对象编程的高级特性:继承、多态、抽象基类、属性装饰器以及元类等。这些概念是构建复杂、可扩展系统的基石,理解它们将帮助你写出更加优雅和强大的Python代码。
一、知识点讲解
1.1 继承基础
继承允许我们基于现有类创建新类,新类继承父类的属性和方法,同时可以添加或覆盖新的功能:
# 基类(父类)
class Animal:
\”\”\”动物基类。\”\”\”
def __init__(self, name, age):
self.name = name
self.age = age
def speak(self):
\”\”\”发出声音,子类应该覆盖此方法。\”\”\”
raise NotImplementedError(\”Subclass must implement speak()\”)
def introduce(self):
\”\”\”自我介绍。\”\”\”
return f\”I am {
self.name}, {
self.age} years old\”
def __str__(self):
return f\”{
self.__class__.__name__}({
self.name}, {
self.age})\”
# 派生类(子类)
class Dog(Animal):
\”\”\”狗类,继承自Animal。\”\”\”
def __init__(self, name, age, breed):
super().__init__(name, age) # 调用父类构造方法
self.breed = breed # 新增属性
def speak(self): # 覆盖父类方法
return f\”{
self.name} says: Woof!\”
def fetch(self): # 新增方法
return f\”{
self.name} is fetching the ball\”
class Cat(Animal):
\”\”\”猫类,继承自Animal。\”\”\”
def __init__(self, name, age, color):
super().__init__(name, age)
self.color = color
def speak(self):
return f\”{
self.name} says: Meow!\”
def climb(self):
return f\”{
self.name} is climbing\”
# 使用示例
dog = Dog(\”Buddy\”, 3, \”Golden Retriever\”)
cat = Cat(\”Whiskers\”, 2, \”Orange\”)
print(dog.introduce()) # 继承自Animal
print(dog.speak()) # Dog自己的实现
print(dog.fetch()) # Dog特有的方法
print(cat.introduce()) # 继承自Animal
print(cat.speak()) # Cat自己的实现
1.2 方法解析顺序(MRO)
当类继承自多个父类时,Python使用C3线性化算法确定方法调用顺序:
class A:
def method(self):
print(\”A.method\”)
return \”A\”
class B(A):
def method(self):
print(\”B.method\”)
result = super().method()
return f\”B -> {
result}\”
class C(A):
def method(self):
print(\”C.method\”)
result = super().method()
return f\”C -> {
result}\”
class D(B, C): # 多重继承
def method(self):
print(\”D.method\”)
result = super().method()
return f\”D -> {
result}\”
# 查看MRO
print(D.__mro__)
# (<class \’__main__.D\’>, <class \’__main__.B\’>,
# <class \’__main__.C\’>, <class \’__main__.A\’>, <class \’object\’>)
# 调用方法
d = D()
print(d.method())
# D.method
# B.method
# C.method
# A.method
# D -> B -> C -> A
1.3 super() 的真正行为
super()不是简单地调用父类方法,而是按照MRO顺序调用下一个类的方法:
class Base:
def __init__(self):
print(\”Base.__init__\”)
self.base_attr = \”base\”
class Middle1(Base):
def __init__(self):
print(\”Middle1.__init__ start\”)
super().__init__() # 调用Base.__init__
self.middle1_attr = \”middle1\”
print(\”Middle1.__init__ end\”)
class Middle2(Base):
def __init__(self):
print(\”Middle2.__init__ start\”)
super().__init__() # 调用Base.__init__
self.middle2_attr = \”middle2\”
print(\”Middle2.__init__ end\”)
class Top(Middle1, Middle2):
def __init__(self):
print(\”Top.__init__ start\”)
super().__init__() # 按照MRO调用Middle1.__init__
self.top_attr = \”top\”
print(\”Top.__init__ end\”)
# 创建实例
t = Top()
print(Top.__mro__)
# 输出顺序:
# Top.__init__ start
# Middle1.__init__ start
# Middle2.__init__ start
# Base.__init__
# Middle2.__init__ end
# Middle1.__init__ end
# Top.__init__ end
关键理解:在协作多重继承中,每个super()调用都会沿着MRO链继续,确保每个类的__init__只被调用一次。
1.4 抽象基类(ABC)
抽象基类定义接口,强制子类实现特定方法:
from abc import ABC, abstractmethod
from typing import List
class Shape(ABC):
\”\”\”形状抽象基类。\”\”\”
@abstractmethod
def area(self) –> float:
\”\”\”计算面积,子类必须实现。\”\”\”
pass
@abstractmethod
def perimeter(self) –> float:
\”\”\”计算周长,子类必须实现。\”\”\”
pass
@property
@abstractmethod
def name(self) –> str:
\”\”\”形状名称。\”\”\”
pass
def describe(self) –> str:
\”\”\”描述形状(具体方法)。\”\”\”
return f\”{
self.name}: area={
self.area():.2f}, perimeter={
self.perimeter():.2f}\”
class Rectangle(Shape):
\”\”\”矩形类。\”\”\”
def __init__(self, width: float, height: float):
self.width = width
self.height = height
@property
def name(self) –> str:
return \”Rectangle\”
def area(self) –> float:
return self.width * self.height
def perimeter(self) –> float:
return 2 * (self.width + self.height)
class Circle(Shape):
\”\”\”圆形类。\”\”\”
def __init__(self, radius: float):
self.radius = radius
@property
def name(self) –> str:
return \”Circle\”
def area(self) –> float:
import math
return math.pi * self.radius ** 2
def perimeter(self) –> float:
import math
return 2 * math.pi * self.radius
# 使用
shapes: List[Shape] = [Rectangle(3, 4), Circle(5)]
for shape in shapes:
print(shape.describe())
# 不能实例化抽象类
# s = Shape() # TypeError: Can\’t instantiate abstract class
1.5 @property 装饰器
@property允许将方法当作属性访问:
class Temperature:
\”\”\”温度类,演示@property的使用。\”\”\”
def __init__(self, celsius: float = 0):
self._celsius = celsius
@property
def celsius(self) –> float:
\”\”\”获取摄氏温度。\”\”\”
return self._celsius
@celsius.setter
def celsius(self, value: float):
\”\”\”设置摄氏温度,带验证。\”\”\”
if value < –273.15:
raise ValueError(\”Temperature below absolute zero is not possible\”)
self._celsius = value
@property
def fahrenheit(self) –> float:
\”\”\”获取华氏温度(只读,通过celsius计算)。\”\”\”
return (self._celsius * 9/5) + 32
@fahrenheit.setter
def fahrenheit(self, value: float):
\”\”\”设置华氏温度,自动转换到摄氏。\”\”\”
self.celsius = (value – 32) * 5/9
@property
def kelvin(self) –> float:
\”\”\”获取开尔文温度。\”\”\”
return self._celsius + 273.15
@kelvin.setter
def kelvin(self, value: float):
\”\”\”设置开尔文温度。\”\”\”
self.celsius = value – 273.15
@property
def is_freezing(self) –> bool:
\”\”\”判断是否冰点以下(只读属性)。\”\”\”
return self._celsius <= 0
# 使用
temp = Temperature(25)
print(f\”Celsius: {
temp.celsius}\”) # 像属性一样访问
print(f\”Fahrenheit: {
temp.fahrenheit}\”)
print(f\”Kelvin: {
temp.kelvin}\”)
temp.celsius = 100 # 像属性一样设置
print(f\”New Fahrenheit: {
temp.fahrenheit}\”)
temp.fahrenheit = 32 # 设置华氏度,自动转换

![[特殊字符]DeepSeek‑Harness(DSH)小白保姆教程-171主机测评](https://www.171host.com/wp-content/uploads/2026/08/20260816085112-6a817a009aabf-220x150.png)