Python 类继承与多态
深入理解继承、super()、方法重写 · 难度:高级 · +15XP
Python 类继承与多态
继承是面向对象编程的核心特性之一,它允许一个类(子类)获得另一个类(父类)的属性和方法。通过继承,我们可以实现代码复用,构建清晰的类层次结构。Python 支持单继承、多继承以及方法重写。
单继承基础
# 父类 (基类)
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} 发出声音"
def eat(self):
return f"{self.name} 正在吃东西"
# 子类 (派生类) 继承 Animal
class Dog(Animal):
def speak(self): # 方法重写
return f"{self.name} 汪汪叫!"
def fetch(self): # 新增方法
return f"{self.name} 正在接飞盘!"
# 使用
dog = Dog('旺财')
print(dog.speak()) # 旺财 汪汪叫!(调用重写的方法)
print(dog.eat()) # 旺财 正在吃东西 (继承的方法)
print(dog.fetch()) # 旺财 正在接飞盘!(新增的方法)
super() 的使用
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
self.species = '人类'
class Student(Person):
def __init__(self, name, age, student_id):
super().__init__(name, age) # 调用父类的 __init__
self.student_id = student_id
def info(self):
return f"{self.name}, {self.age}岁, 学号: {self.student_id}"
stu = Student('小明', 20, '2024001')
print(stu.info()) # 小明, 20岁, 学号: 2024001
print(stu.species) # 人类 (继承自父类)
多重继承
class Flyable:
def fly(self):
return "可以飞行"
class Swimmable:
def swim(self):
return "可以游泳"
class Duck(Flyable, Swimmable):
def quack(self):
return "嘎嘎叫!"
duck = Duck()
print(duck.fly()) # 可以飞行
print(duck.swim()) # 可以游泳
print(duck.quack()) # 嘎嘎叫!
多态
多态意味着不同的类可以实现相同名称的方法,调用时根据对象的实际类型执行不同的行为:
class Cat:
def sound(self):
return "喵喵"
class Dog:
def sound(self):
return "汪汪"
class Cow:
def sound(self):
return "哞哞"
# 多态调用
def animal_sound(animal):
print(animal.sound())
animals = [Cat(), Dog(), Cow()]
for a in animals:
animal_sound(a) # 分别输出: 喵喵 汪汪 哞哞
方法解析顺序(MRO)
Python 使用 C3 线性化算法来确定多重继承时方法的查找顺序:
class A: pass
class B(A): pass
class C(A): pass
class D(B, C): pass
print(D.__mro__)
# (D, B, C, A, object)
继承相关函数速查表
| 函数 | 说明 |
|---|---|
| isinstance(obj, Class) | 检查 obj 是否为 Class 的实例 |
| issubclass(Child, Parent) | 检查 Child 是否为 Parent 的子类 |
| super() | 返回父类的代理对象 |
| __mro__ | 查看方法解析顺序 |
| __bases__ | 查看直接父类 |