Python中重载运算符是通过定义特殊方法来实现的,这些方法通常以双下划线开头和结尾,例如`__add__`、`__sub__`等。当Python的内置操作符应用于类的对象时,Python会自动调用这些特殊方法。
`__add__`/`__sub__`:加减运算
`__mul__`/`__truediv__`/`__floordiv__`/`__mod__`/`__pow__`:乘除和取模运算
`__eq__`/`__ne__`/`__lt__`/`__le__`/`__gt__`/`__ge__`:比较运算
`__add__`/`__sub__`/`__mul__`/`__truediv__`/`__floordiv__`/`__mod__`/`__pow__`:反向运算符(例如`a + b`中的`b + a`)
`__repr__`/`__str__`:打印/转换
`__call__`:函数调用
`__getitem__`:索引运算
重载运算符可以让自定义类的对象像内置类型一样进行运算,从而简化代码并提高程序的可读性。
例如,下面是一个简单的`Vector`类,演示了如何重载加法运算符:
```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)
elif isinstance(other, (int, float)):
return Vector(self.x + other, self.y)
else:
raise TypeError("Unsupported operand type for +")
def __str__(self):
return f"({self.x}, {self.y})"
创建两个向量对象
v1 = Vector(1, 2)
v2 = Vector(3, 4)
向量加法
result_add = v1 + v2
print(f"Vector addition result: {result_add}")
在这个例子中,`Vector`类重载了加法运算符`+`,使得两个`Vector`对象可以相加,并返回一个新的`Vector`对象,其坐标是两个向量对应坐标的和。
需要注意的是,重载运算符时,应该确保操作符的行为符合预期,并且不会与Python的内置行为冲突。