第6章:类与OOP(Classes and OOP)
一、导读
1.1 本章学习目标
第6章讲解 Python 的面向对象编程。Python 的 OOP 系统灵活而强大。
1.2 为什么第六章如此重要
面向对象是 Python 的核心范式。理解类、继承、多态是掌握 Python 的关键。
1.3 核心问题引导
Python 的类如何定义?
继承如何实现?
多态在 Python 中如何体现?
运算符重载如何使用?
二、核心概念详解
6.1 类定义
python
class Dog:
# 类变量
species = "Canine"
# 构造方法
def __init__(self, name, age):
self.name = name # 实例变量
self.age = age
# 实例方法
def bark(self):
return f"{self.name} says Woof!"
# 类方法
@classmethod
def from_birth_year(cls, name, birth_year):
return cls(name, 2024 - birth_year)
# 静态方法
@staticmethod
def is_mammal():
return True
def __str__(self):
return f"Dog({self.name}, {self.age})"
def __repr__(self):
return f"Dog(name='{self.name}', age={self.age})"
dog = Dog("Rex", 5)
print(dog.bark()) # Rex says Woof!6.2 继承
python
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError
class Dog(Animal):
def speak(self):
return f"{self.name}: Woof!"
class Cat(Animal):
def speak(self):
return f"{self.name}: Meow!"
# 多态
animals = [Dog("Rex"), Cat("Kitty")]
for animal in animals:
print(animal.speak())
# super()
class Puppy(Dog):
def __init__(self, name, trick):
super().__init__(name)
self.trick = trick
# 方法解析顺序(MRO)
print(Puppy.__mro__)6.3 运算符重载
python
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __mul__(self, scalar):
return Vector(self.x * scalar, self.y * scalar)
def __abs__(self):
return (self.x**2 + self.y**2)**0.5
def __eq__(self, other):
return self.x == other.x and self.y == other.y
def __repr__(self):
return f"Vector({self.x}, {self.y})"
v1 = Vector(3, 4)
v2 = Vector(1, 2)
print(v1 + v2) # Vector(4, 6)
print(v1 * 3) # Vector(9, 12)
print(abs(v1)) # 5.06.4 属性管理
python
class Temperature:
def __init__(self, celsius=0):
self._celsius = celsius
@property
def celsius(self):
return self._celsius
@celsius.setter
def celsius(self, value):
if value < -273.15:
raise ValueError("Below absolute zero!")
self._celsius = value
@property
def fahrenheit(self):
return self._celsius * 9/5 + 32
temp = Temperature(25)
temp.celsius = 30 # 使用 setter
print(temp.fahrenheit) # 86.0三、实战案例
6.1 数据类
python
from dataclasses import dataclass
@dataclass
class Point:
x: float
y: float
z: float = 0.0
def distance(self, other):
return ((self.x - other.x)**2 +
(self.y - other.y)**2 +
(self.z - other.z)**2)**0.5
p1 = Point(1, 2, 3)
p2 = Point(4, 5, 6)
print(p1.distance(p2)) # 5.196...
print(p1) # Point(x=1, y=2, z=3)四、本章小结
Python 的 OOP 系统灵活强大。支持类、继承、多态、运算符重载。使用 @property 管理属性,@dataclass 简化数据类。
五、思考与练习
Python 的类如何定义?
继承如何实现?super() 的作用是什么?
多态在 Python 中如何体现?
运算符重载有哪些常用方法?
@property 的作用是什么?