17370845950

python3代码中如何实现加法重载?
通过定义__add__方法可实现Python中的加法重载,该方法在使用+运算符时自动调用,接收self和other参数并返回新对象;示例中Number类通过__add__支持Number与Number或数值类型的相加,并通过__radd__支持右加法如int+Number;类型不支持时应返回NotImplemented以允许Python尝试其他方法,保持操作的对称性与数学直觉。

在 Python3 中,可以通过定义类中的特殊方法 __add__ 来实现加法重载。这个方法会在使用 + 运算符时被自动调用。

定义 __add__ 方法

当你在自定义类中实现 __add__ 方法时,可以指定两个对象相加的逻辑。该方法接收两个参数:selfother,分别表示参与加法的两个操作数。

返回一个新的对象或合适的值,避免修改原始对象。

示例代码:

class Number:
    def __init__(self, value):
        self.value = value
def __add__(self, other):
    if isinstance(other, Number):
        return Number(self.value + other.value)
    elif isinstance(other, (int, float)):
        return Number(self.value + other)
    return NotImplemented

def __repr__(self):
    return f"Number({self.value})"

使用示例

a = Number(5) b = Number(3) print(a + b) # 输出: Number(8) print(a + 10) # 输出: Number(15)

支持反向加法(右操作数)

如果左操作数不支持加法,Python 会尝试调用右操作数的 __radd__ 方法。为了支持像 int + Number 这样的表达式,建议实现它。

    def __radd__(self, other):
        # 右加法:other + self
        if isinstance(other, (int, float)):
            return Number(other + self.value)
        return NotImplemented

加上这个方法后,5 + Number(3) 也能正确运行,结果为 Number(8)

注意事项

确保类型检查合理,不支持的操作应返回 NotImplemented,而不是抛出异常,这样 Python 可以尝试其他方式处理运算。

保持操作的对称性和可预测性,让加法符合数学直觉。

基本上就这些。