2026-03-25 21:40:32
Python运算符重载通过在类中定义特殊方法(如__add__)实现,允许自定义对象对运算符的行为。以下是一个完整实例及扩展说明:
基础实例:加法运算符重载class Test: def __init__(self, value): self.value = value def __add__(self, other): return self.value + other.valuea = Test(3)b = Test(4)print(a + b) # 输出:7方法名必须为__add__(双下划线包裹)。
参数self表示当前对象,other表示右侧操作数。
返回值为运算结果(此处为两对象value属性的和)。
以下示例展示如何重载加法、减法、比较运算符及字符串表示:
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) # 比较运算符(等于) def __eq__(self, other): return self.x == other.x and self.y == other.y # 字符串表示 def __str__(self): return f"Vector({self.x}, {self.y})"v1 = Vector(2, 3)v2 = Vector(4, 1)print(v1 + v2) # 输出:Vector(6, 4)print(v1 - v2) # 输出:Vector(-2, 2)print(v1 == v2) # 输出:Falseprint(v1) # 输出:Vector(2, 3)算术运算符:
+ → __add__
- → __sub__
* → __mul__
/ → __truediv__
比较运算符:
== → __eq__
!= → __ne__
< → __lt__
其他常用方法:
__str__:定义对象的字符串表示形式。
__repr__:定义对象的官方字符串表示(通常用于调试)。
通过运算符重载,可以显著提升自定义对象的易用性,使其更符合直觉的数学或逻辑操作。