在 Python 中,如何实现运算符重载(Operator Overloading)
在 Python 中,**运算符重载(Operator Overloading)**允许你为自定义类定义运算符的行为,比如 +、-、==、< 等。它通过 特殊方法(魔术方法) 实现,如 __add__()、__eq__() 等。
一、基本示例:重载 + 运算符
以一个自定义的二维向量类 Vector2D 为例:
class Vector2D:
def __init__(self, x, y):
self.x = x
self.y = y
# 重载 + 运算符
def __add__(self, other):
return Vector2D(self.x + other.x, self.y + other.y)
def __repr__(self):
return f"Vector2D({self.x}, {self.y})"
# 测试
v1 = Vector2D(1, 2)
v2 = Vector2D(3, 4)
print(v1 + v2) # 输出:Vector2D(4, 6)
二、常用运算符及其魔术方法对照表
| 运算符 | 魔术方法 | 描述 |
|---|---|---|
+ | __add__(self, other) | 加法 |
- | __sub__ | 减法 |
* | __mul__ | 乘法 |
/ | __truediv__ | 除法(真除法) |
// | __floordiv__ | 地板除 |
% | __mod__ | 取模 |
** | __pow__ | 幂运算 |
== | __eq__ | 等于 |
!= | __ne__ | 不等于 |
< | __lt__ | 小于 |
<= | __le__ | 小于等于 |
> | __gt__ | 大于 |
>= | __ge__ | 大于等于 |
三、进一步示例:重载 == 和 <
class Student:
def __init__(self, name, score):
self.name = name
self.score = score
def __eq__(self, other):
return self.score == other.score
def __lt__(self, other):
return self.score < other.score
# 测试
s1 = Student("Alice", 90)
s2 = Student("Bob", 85)
print(s1 == s2) # False
print(s1 < s2) # False
四、注意事项
- 类型检查是个好习惯:
def __add__(self, other):
if isinstance(other, Vector2D):
return Vector2D(self.x + other.x, self.y + other.y)
return NotImplemented
- 应始终实现成对的方法(如实现了
__eq__,最好也实现__ne__) - 不可滥用重载:避免过度重载造成代码难以理解。
五、出站参考链接
六、总结
| 特性 | 说明 |
|---|---|
| 灵活性高 | 可为类自定义运算行为 |
| 使用魔术方法 | 如 __add__, __eq__ |
| 用于自定义类 | 适合 向量/矩阵/复数/模型对象 |
| 推荐搭配使用 | __str__、__repr__ 更易调试 |
更多详细内容请关注其他相关文章!