

> 📖 **一起读书吧!** 加入《Python编程:从入门到实践》共读营 👉 [点击参加](https://mp.weixin.qq.com/s/ehe2vMrfAFscRLqbM9TF-g)本讲内容
- 单继承:子类继承父类
- 方法重写(override)
- super() 调用父类方法
- 多态:同一接口,不同行为
- 导入类和模块
学习目标
像搭乐高一样扩展功能 🧱
1. 继承基础
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| class Car: """父类:汽车""" def __init__(self, make, model, year): self.make = make self.model = model self.year = year self.odometer = 0
def get_description(self): return f"{self.year} {self.make} {self.model}"
class ElectricCar(Car): """子类:电动汽车""" def __init__(self, make, model, year): super().__init__(make, model, year) self.battery_size = 75
def describe_battery(self): print(f"电池容量:{self.battery_size} kWh")
my_tesla = ElectricCar('tesla', 'model s', 2024) print(my_tesla.get_description()) my_tesla.describe_battery()
|
super().__init__() 让父类帮忙初始化,子类只管自己的新增部分。
官方文档:9.5. Inheritance
2. 方法重写
1 2 3 4 5 6 7 8 9 10
| class Car: def fill_gas_tank(self): print("加满油!")
class ElectricCar(Car): def fill_gas_tank(self): print("电动汽车不需要加油!")
ec = ElectricCar('tesla', 'model 3', 2024) ec.fill_gas_tank()
|
3. 将实例用作属性
当一个类变得太大时,把部分功能拆成独立类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| class Battery: """电池类""" def __init__(self, battery_size=75): self.battery_size = battery_size
def describe_battery(self): print(f"电池容量:{self.battery_size} kWh")
def get_range(self): if self.battery_size == 75: range = 260 elif self.battery_size == 100: range = 315 print(f"满电续航:约 {range} 英里")
class ElectricCar(Car): def __init__(self, make, model, year): super().__init__(make, model, year) self.battery = Battery()
|
4. 多态示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| class Animal: def speak(self): raise NotImplementedError
class Dog(Animal): def speak(self): return "汪汪!"
class Cat(Animal): def speak(self): return "喵喵!"
animals = [Dog(), Cat(), Dog()] for animal in animals: print(animal.speak())
|
5. isinstance() 检查类型
1 2 3 4 5 6
| e = ElectricCar('tesla', 'model 3', 2024) c = Car('丰田', '卡罗拉', 2024)
print(isinstance(e, ElectricCar)) print(isinstance(e, Car)) print(isinstance(c, ElectricCar))
|
官方文档:isinstance()
6. 导入类
1 2 3 4 5 6 7 8 9
| from car import Car, ElectricCar
import car c = car.Car('丰田', '卡罗拉', 2024)
from car import *
|
官方文档:6. Modules — 模块就是 .py 文件。
📚 官方文档参考
🎓 AI 编程实战课程
程序员晚枫专注AI编程培训,通过 《30讲 · AI编程训练营》,让小白也能用AI做出实际项目。