主题
Python 面向对象编程
本文介绍 Python 的类与对象模型:类定义、继承、魔术方法、数据类与多态。
作者:yanshaodong
类与实例
python
class Person:
species = "Homo sapiens" # 类属性
def __init__(self, name, age):
self.name = name # 实例属性
self.age = age
def introduce(self):
return f"我是 {self.name},{self.age} 岁"
p = Person("Alice", 18)
print(p.introduce())
print(Person.species)封装与属性
Python 用命名约定表达可见性:_name(受保护)、__name(名称改写,伪私有)。
python
class Account:
def __init__(self, balance):
self.__balance = balance
@property
def balance(self):
return self.__balance
@balance.setter
def balance(self, value):
if value < 0:
raise ValueError("余额不能为负")
self.__balance = valueproperty 把方法变成可读/可写属性,方便校验。
继承与多态
python
class Animal:
def speak(self):
raise NotImplementedError
class Dog(Animal):
def speak(self):
return "汪汪"
class Cat(Animal):
def speak(self):
return "喵喵"
for a in [Dog(), Cat()]:
print(a.speak()) # 多态:统一接口,不同行为多重继承与 MRO
python
class A: pass
class B(A): pass
class C(A): pass
class D(B, C): pass
print(D.__mro__) # 方法解析顺序Python 使用 C3 线性化算法决定 MRO,避免菱形继承歧义。super() 遵循 MRO 调用下一个类。
魔术方法(Dunder)
通过实现特殊方法,让自定义对象像内建类型一样工作:
python
class Vector:
def __init__(self, x, y):
self.x, self.y = x, y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __repr__(self):
return f"Vector({self.x}, {self.y})"
def __len__(self):
return 2
v = Vector(1, 2) + Vector(3, 4)
print(v) # Vector(4, 6)常用:__str__ / __repr__、__eq__ / __lt__、__getitem__、__iter__、__call__、__enter__ / __exit__(上下文管理器)。
数据类 dataclass
python
from dataclasses import dataclass
@dataclass
class Point:
x: float
y: float
def norm(self):
return (self.x ** 2 + self.y ** 2) ** 0.5
p = Point(3, 4)
print(p) # Point(x=3, y=4)dataclass 自动生成 __init__、__repr__、__eq__,适合纯数据载体。
抽象基类 ABC
python
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
...
class Circle(Shape):
def area(self):
return 3.14 * self.r ** 2小结
- 实例属性在
__init__中初始化;类属性被所有实例共享。 property提供带校验的属性访问。- 多态依赖鸭子类型与统一接口;
super()按 MRO 调用。 - 魔术方法让自定义类型融入 Python 语法。
dataclass与ABC分别简化数据载体与接口约束。