在Python中,运算符重载是通过定义特殊方法来实现的,这些方法允许对象对内置运算符的行为进行自定义。以下是一些常见的运算符重载方法及其对应的运算符符号:
__add__(self, other):定义加法运算符 +__sub__(self, other):定义减法运算符 -__mul__(self, other):定义乘法运算符 *__truediv__(self, other) 或 __div__(self, other)(Python 2):定义除法运算符 / 或 //(Python 3中只使用__truediv__)__floordiv__(self, other):定义整除运算符 //(Python 3)__mod__(self, other):定义取模运算符 %__pow__(self, other[, modulo]):定义乘方运算符 **__eq__(self, other):定义等于运算符 ==__ne__(self, other):定义不等于运算符 !=__lt__(self, other):定义小于运算符 <__le__(self, other):定义小于等于运算符 <=__gt__(self, other):定义大于运算符 >__ge__(self, other):定义大于等于运算符 >=__invert__(self):定义按位取反运算符 ~__and__(self, other):定义按位与运算符 &__or__(self, other):定义按位或运算符 |__xor__(self, other):定义按位异或运算符 ^__lshift__(self, other):定义左移运算符 <<__rshift__(self, other):定义右移运算符 >>Python不直接支持运算符重载来处理赋值操作,但可以通过定义相应的属性来实现类似的效果。
__getitem__(self, key):定义索引运算符 []__setitem__(self, key, value):定义索引赋值运算符 [] =__delitem__(self, key):定义删除索引运算符 del []__contains__(self, item):定义成员运算符 in运算符重载在许多场景中都非常有用,例如:
以下是一个简单的示例,演示如何使用运算符重载来创建一个自定义的向量类:
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 __str__(self):
return f"({self.x}, {self.y})"
# 使用示例
v1 = Vector(1, 2)
v2 = Vector(3, 4)
v3 = v1 + v2
print(v3) # 输出:(4, 6)在这个示例中,我们定义了一个Vector类,并重载了加法运算符+,使得两个向量对象可以相加。
请注意,以上链接可能会随着Python版本的更新而发生变化,建议在需要时查阅最新的官方文档。