Skip to main content
 首页 » 编程设计

python之Python中不同类型操作数的重载运算符

2024年11月01日8lautakyan007

考虑以下表示向量的“包装器”类示例:

class Vector: 
 
    def __init__(self, value): 
        self._vals = value.copy() 
 
 
    def __add__(self, other): 
 
        if isinstance(other, list): 
            result = [x+y for (x, y) in zip(self._vals, other)] 
        elif isinstance(other, Vector): 
            result = [x+y for (x, y) in zip(self._vals, other._vals)] 
        else: 
            # assume other is scalar 
            result = [x+other for x in self._vals] 
 
        return Vector(result) 
 
    def __str__(self): 
        return str(self._vals) 

__add__ 方法负责添加两个向量以及添加带有标量的向量。然而,第二种情况并不完整,如下例所示:

>>> a = Vector([1.2, 3, 4]) 
>>> print(a) 
[1.2, 3, 4] 
>>> print(a+a) 
[2.4, 6, 8] 
>>> print(a+5) 
[6.2, 8, 9] 
>>> print(5+a) 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
TypeError: unsupported operand type(s) for +: 'int' and 'Vector' 

据我了解,原因是重载运算符只告诉 Python 在看到 a + x 时该做什么,其中 a 是 Vector< 的一个实例,但没有指示要为 x + a 做什么(a 是 Vector 和 x 的实例 一个标量)。

在这种情况下应该如何重载运算符以涵盖所有情况(即,支持 self 不是 Vector 而是 other 的实例的情况 是)?

请您参考如下方法:

好的。我想我找到了答案:还必须重载 __radd__ 运算符:

class Vector: 
 
    def __init__(self, value): 
        self._vals = value.copy() 
 
 
    def __add__(self, other): 
 
        if isinstance(other, list): 
            result = [x+y for (x, y) in zip(self._vals, other)] 
        elif isinstance(other, Vector): 
            result = [x+y for (x, y) in zip(self._vals, other._vals)] 
        else: 
            # assume other is scalar 
            result = [x+other for x in self._vals] 
 
        return Vector(result) 
 
    def __radd__(self, other): 
        return self + other 
 
 
    def __str__(self): 
        return str(self._vals) 

虽然对我来说这看起来有点多余。 (为什么 Python 默认不使用加法的交换性,假设 __radd__(self, other) 总是返回 self + other?当然对于特殊情况,用户可以重写 __radd__。)