python 自定义运算符
时间: 2025-03-03 10:13:25 浏览: 53
### 定义自定义运算符
Python本身不支持直接创建新的运算符,但可以通过重载现有运算符实现特定功能。这主要通过在类中定义特殊方法完成。例如:
#### 加法运算符 `+`
当希望两个对象相加时可以这样做:
```python
class Vector:
def __init__(self, components):
self.components = components
def __add__(self, other):
if len(self.components) != len(other.components):
raise ValueError("Vectors must be of same dimension")
result_components = [sum(x) for x in zip(self.components, other.components)]
return Vector(result_components)
v1 = Vector([1, 2])
v2 = Vector([3, 4])
print((v1 + v2).components) # 输出: [4, 6]
```
上述代码展示了如何利用`__add__()`方法来定制向量之间的加法规则[^1]。
对于一元操作符如负号 `-`, 可以使用`__neg__()`:
```python
def __neg__(self):
negated_components = [-x for x in self.components]
return Vector(negated_components)
```
#### 自定义索引访问行为
如果想要改变实例被下标访问的方式,则需覆盖`__getitem__()` 和/或 `__setitem__()` 方法:
```python
class CustomList(list):
def __getitem__(self, index):
print(f"Accessing element at position {index}")
return super().__getitem__(index)
cl = CustomList(['a', 'b', 'c'])
print(cl[1]) # Accessing element at position 1\n'b'
```
值得注意的是,并不是所有的内置语法结构都能如此轻易地修改其默认行为。像切片这样的复杂表达式虽然也可以处理,但是涉及更多细节上的考量。
阅读全文
相关推荐

















