Python中有哪些特殊方法
# Python中有哪些特殊方法
## 目录
1. [特殊方法概述](#特殊方法概述)
2. [对象生命周期相关方法](#对象生命周期相关方法)
3. [数值运算相关方法](#数值运算相关方法)
4. [类型转换方法](#类型转换方法)
5. [容器类型方法](#容器类型方法)
6. [属性访问控制方法](#属性访问控制方法)
7. [可调用对象方法](#可调用对象方法)
8. [上下文管理方法](#上下文管理方法)
9. [描述符协议方法](#描述符协议方法)
10. [比较操作相关方法](#比较操作相关方法)
11. [其他重要特殊方法](#其他重要特殊方法)
12. [实际应用案例](#实际应用案例)
13. [总结](#总结)
## 特殊方法概述
Python中的特殊方法(Special Methods),也称为魔术方法(Magic Methods)或双下方法(Dunder Methods),是以双下划线开头和结尾的方法。这些方法允许开发者自定义类的行为,使其能够与Python内置的操作符和函数无缝集成。
```python
class Example:
def __init__(self, value):
self.value = value
def __str__(self):
return f"Example with value: {self.value}"
特殊方法的主要特点:
- 由Python解释器自动调用
- 实现特定的语言功能
- 命名遵循__xxx__模式
- 不可直接调用(除非明确知道其用途)
对象生命周期相关方法
__new__ 和 __init__
class MyClass:
def __new__(cls, *args, **kwargs):
print("Creating instance")
instance = super().__new__(cls)
return instance
def __init__(self, value):
print("Initializing instance")
self.value = value
__new__: 负责实例创建(类方法)
__init__: 负责实例初始化
- 关系:
__new__返回实例 → __init__初始化该实例
__del__
class Resource:
def __del__(self):
print("Cleaning up resources")
- 对象被垃圾回收时调用
- 不应用于重要资源清理(时机不确定)
- 建议使用上下文管理器或显式清理方法
数值运算相关方法
基本算术运算
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 __sub__(self, other):
return Vector(self.x - other.x, self.y - other.y)
| 方法 |
操作符 |
描述 |
__add__ |
+ |
加法 |
__sub__ |
- |
减法 |
__mul__ |
* |
乘法 |
__truediv__ |
/ |
真除法 |
__floordiv__ |
// |
地板除 |
反向运算和就地运算
class Vector:
def __radd__(self, other):
return self.__add__(other)
def __iadd__(self, other):
self.x += other.x
self.y += other.y
return self
- 反向方法(如
__radd__):当左操作数不支持操作时调用
- 就地方法(如
__iadd__):实现+=等操作
类型转换方法
基本类型转换
class Temperature:
def __init__(self, celsius):
self.celsius = celsius
def __int__(self):
return int(self.celsius)
def __float__(self):
return float(self.celsius)
| 方法 |
调用方式 |
__bool__ |
bool(obj) |
__int__ |
int(obj) |
__float__ |
float(obj) |
__complex__ |
complex(obj) |
字符串表示
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"Point({self.x}, {self.y})"
def __repr__(self):
return f"Point(x={self.x}, y={self.y})"
__str__: 用户友好字符串(str()和print())
__repr__: 开发者友好字符串(repr()和交互式解释器)
__format__: 支持格式化字符串(format()和f-string)
容器类型方法
序列协议方法
class MyList:
def __init__(self, data):
self.data = list(data)
def __getitem__(self, index):
return self.data[index]
def __len__(self):
return len(self.data)
def __contains__(self, item):
return item in self.data
| 方法 |
操作 |
__len__ |
len(obj) |
__getitem__ |
obj[index] |
__setitem__ |
obj[index] = value |
__delitem__ |
del obj[index] |
__contains__ |
item in obj |
映射类型方法
class MyDict:
def __keys__(self):
return list(self.data.keys())
def __getitem__(self, key):
return self.data[key]
def __setitem__(self, key, value):
self.data[key] = value
属性访问控制方法
基本属性访问
class Person:
def __getattribute__(self, name):
print(f"Accessing {name}")
return super().__getattribute__(name)
def __setattr__(self, name, value):
print(f"Setting {name} = {value}")
super().__setattr__(name, value)
def __delattr__(self, name):
print(f"Deleting {name}")
super().__delattr__(name)
| 方法 |
调用场景 |
__getattr__ |
属性不存在时 |
__getattribute__ |
所有属性访问 |
__setattr__ |
属性赋值时 |
__delattr__ |
删除属性时 |
可调用对象方法
class Adder:
def __init__(self, n):
self.n = n
def __call__(self, x):
return self.n + x
add5 = Adder(5)
print(add5(10)) # 输出15
__call__: 使实例可像函数一样调用
- 应用场景:装饰器类、状态保持函数
上下文管理方法
class FileHandler:
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
def __enter__(self):
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
self.file.close()
if exc_type:
print(f"Exception handled: {exc_val}")
__enter__: 进入上下文时调用
__exit__: 离开上下文时调用
- 支持
with语句
描述符协议方法
class ValidatedAttribute:
def __init__(self, name):
self.name = name
def __get__(self, instance, owner):
return instance.__dict__[self.name]
def __set__(self, instance, value):
if not isinstance(value, int):
raise TypeError("Expected int")
instance.__dict__[self.name] = value
| 方法 |
描述 |
__get__ |
获取属性值时调用 |
__set__ |
设置属性值时调用 |
__delete__ |
删除属性时调用 |
比较操作相关方法
class Money:
def __init__(self, amount, currency):
self.amount = amount
self.currency = currency
def __eq__(self, other):
return (self.amount == other.amount and
self.currency == other.currency)
def __lt__(self, other):
if self.currency != other.currency:
raise ValueError("Cannot compare different currencies")
return self.amount < other.amount
| 方法 |
操作符 |
反向方法 |
__eq__ |
== |
|
__ne__ |
!= |
|
__lt__ |
< |
__gt__ |
__le__ |
<= |
__ge__ |
其他重要特殊方法
类创建控制
class Meta(type):
def __new__(cls, name, bases, namespace):
print(f"Creating class {name}")
return super().__new__(cls, name, bases, namespace)
class MyClass(metaclass=Meta):
pass
__new__: 控制类创建过程
__init_subclass__: 子类初始化时调用
异步支持
class AsyncReader:
async def __aenter__(self):
self.file = await aiofiles.open(...)
return self
async def __aexit__(self, *args):
await self.file.close()
__await__: 实现可等待对象
__aiter__, __anext__: 异步迭代
__aenter__, __aexit__: 异步上下文管理器
实际应用案例
实现向量类
class Vector:
def __init__(self, *components):
self.components = components
def __add__(self, other):
if len(self.components) != len(other.components):
raise ValueError("Vectors must be same dimension")
new_components = [
x + y for x, y in zip(self.components, other.components)
]
return Vector(*new_components)
def __mul__(self, scalar):
if isinstance(scalar, (int, float)):
return Vector(*[x * scalar for x in self.components])
raise TypeError("Can only multiply by scalar")
def __abs__(self):
return sum(x**2 for x in self.components) ** 0.5
def __str__(self):
return f"Vector{self.components}"
实现上下文管理器
class Timer:
def __enter__(self):
self.start = time.time()
return self
def __exit__(self, *args):
self.end = time.time()
self.elapsed = self.end - self.start
print(f"Elapsed time: {self.elapsed:.2f} seconds")
# 使用示例
with Timer() as t:
time.sleep(1.5)
总结
Python的特殊方法提供了强大的能力来定制类的行为,使其能够与Python语言结构无缝集成。关键要点:
- 特殊方法实现了操作符重载、类型转换、容器行为等核心功能
- 命名约定为双下划线开头和结尾
- 由Python解释器自动调用
- 合理使用可以创建直观、Pythonic的API
- 过度使用可能导致代码难以理解
掌握这些特殊方法是成为Python高级开发者的重要一步,它们使得自定义类型能够像内置类型一样自然工作。
# 最终示例:综合使用多个特殊方法
class Polynomial:
def __init__(self, coefficients):
self.coeffs = coefficients
def __call__(self, x):
return sum(coeff * (x ** i)
for i, coeff in enumerate(self.coeffs))
def __add__(self, other):
max_len = max(len(self.coeffs), len(other.coeffs))
new_coeffs = [
(self.coeffs[i] if i < len(self.coeffs) else 0) +
(other.coeffs[i] if i < len(other.coeffs) else 0)
for i in range(max_len)
]
return Polynomial(new_coeffs)
def __str__(self):
terms = []
for i, coeff in enumerate(self.coeffs):
if coeff == 0:
continue
term = f"{coeff}"
if i > 0:
term += "x" + (f"^{i}" if i > 1 else "")
terms.append(term)
return " + ".join(reversed(terms)) or "0"
通过灵活组合这些特殊方法,可以创建出功能强大且易于使用的自定义类,这正是Python语言优雅和强大之处。
“`