Python运算符重载用法实例

Python运算符重载用法实例
最新回答
说不尽的伤ミ

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
  • 核心机制:当执行a + b时,Python自动调用a.__add__(b),即调用Test类中定义的__add__方法。
  • 关键点

    方法名必须为__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__:定义对象的官方字符串表示(通常用于调试)。

反向运算符与就地运算符
  1. 反向运算符:当左侧对象未实现运算符时,Python尝试调用右侧对象的反向方法(如__radd__):
class Number: def __init__(self, value): self.value = value def __radd__(self, other): return self.value + other # 支持 int + Numbern = Number(10)print(5 + n) # 输出:15(调用 n.__radd__(5))
  1. 就地运算符:直接修改对象自身(如+=对应__iadd__):
class Counter: def __init__(self, count): self.count = count def __iadd__(self, other): self.count += other return self # 必须返回 self 以支持连续操作c = Counter(5)c += 3print(c.count) # 输出:8注意事项
  • 方法签名固定:运算符重载方法必须严格遵循命名规范(如__add__,不可自定义名称)。
  • 返回值类型:通常返回新对象(如加法),但就地运算符(如__iadd__)需返回self。
  • 类型检查:建议在重载方法中检查other的类型,避免意外错误:
def __add__(self, other): if not isinstance(other, Test): raise TypeError("操作数必须是Test类型") return self.value + other.value完整代码示例class Point: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): if isinstance(other, Point): return Point(self.x + other.x, self.y + other.y) elif isinstance(other, (int, float)): return Point(self.x + other, self.y + other) else: raise TypeError("不支持的操作数类型") def __str__(self): return f"Point({self.x}, {self.y})"p1 = Point(1, 2)p2 = Point(3, 4)print(p1 + p2) # 输出:Point(4, 6)print(p1 + 5) # 输出:Point(6, 7)

通过运算符重载,可以显著提升自定义对象的易用性,使其更符合直觉的数学或逻辑操作。