在Python中,重载运算符是通过定义特殊方法来实现的。这些方法以双下划线开头和结尾,例如`__add__`。当Python中的对象使用这些运算符时,会自动调用对应的方法。下面是一些常见的运算符及其对应的重载方法:
加法(`+`): `__add__`
减法(`-`): `__sub__`
乘法(`*`): `__mul__`
除法(`/`): `__truediv__`
求模(`%`): `__mod__`
幂(` `): `__pow__`
比较(`==`、`!=`、`<`、`>`、`<=`、`>=`): `__eq__`、`__ne__`、`__lt__`、`__gt__`、`__le__`、`__ge__`
一元运算符(`-`、`~`、`abs()`): `__neg__`、`__pos__`、`__abs__`
下面是一个简单的例子,展示如何重载加法运算符:
```python
class CustomSequence:
def __init__(self, items=None):
self.items = items or []
def __add__(self, other):
if not isinstance(other, CustomSequence):
raise TypeError("Unsupported operand type(s)")
return CustomSequence(self.items + other.items)
def __len__(self):
return len(self.items)
def __getitem__(self, index):
return self.items[index]
使用例子
seq1 = CustomSequence([1, 2, 3])
seq2 = CustomSequence([4, 5, 6])
combined_seq = seq1 + seq2[1:3] 通过重载加法运算符连接两个序列
在这个例子中,`CustomSequence`类重载了加法运算符`+`,使得两个`CustomSequence`对象可以通过加法运算符连接起来。
需要注意的是,Python对运算符重载有一定的限制,例如不能重载内置类型的运算符,不能创建新的运算符,只能重载现有的运算符,并且某些运算符如`is`、`and`、`or`、`not`不能被重载。