在Python中,运算符重载是通过定义特殊方法(也称为魔术方法)来实现的,这些特殊方法允许类的实例像内置类型那样使用运算符。
Python提供了一系列这样的特殊方法,用于重载各种运算符。
以下是一些常见的运算符重载特殊方法及其对应的运算符:
add(self, other):重载加法运算符 +
sub(self, other):重载减法运算符 -
mul(self, other):重载乘法运算符 *
truediv(self, other):重载真除法运算符 /(在Python 3中)
floordiv(self, other):重载整除法运算符 //
mod(self, other):重载取模运算符 %
pow(self, other[, modulo]):重载幂运算符 **
radd(self, other):重载右加法运算符(用于反向操作,例如当左侧操作数不是该类的实例时)
iadd(self, other):重载就地加法运算符(用于 +=)
eq(self, other):重载等于运算符 ==
ne(self, other):重载不等于运算符 !=
lt(self, other):重载小于运算符 <
le(self, other):重载小于等于运算符 <=
gt(self, other):重载大于运算符 >
ge(self, other):重载大于等于运算符 >=
以下是一个简单的Python示例,展示了如何重载加法运算符 + 和等于运算符 ==:
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
if isinstance(other, Vector):
return Vector(self.x + other.x, self.y + other.y)
return NotImplemented
def __eq__(self, other):
if isinstance(other, Vector):
return self.x == other.x and self.y == other.y
return NotImplemented
def __repr__(self):
return f"Vector({self.x}, {self.y})"
# 使用示例
v1 = Vector(2, 3)
v2 = Vector(4, 5)
v3 = v1 + v2 # 调用 __add__ 方法
print(v3) # 输出: Vector(6, 8)
v4 = Vector(2, 3)
print(v1 == v4) # 输出: True
print(v1 == v2) # 输出: False
在这个例子中,Vector 类定义了两个特殊方法:add 和 eq。add 方法用于重载加法运算符,允许两个 Vector 实例相加。eq 方法用于重载等于运算符,允许比较两个 Vector 实例是否相等。
注意,当重载运算符时,如果操作数类型不匹配,通常应该返回 NotImplemented,这样Python可以尝试使用反向运算符(例如,如果 a + b 不匹配,则尝试 b.radd(a))。这是Python运算符重载的一个约定俗成的做法,有助于保持代码的灵活性和健壮性。