← 中文资源

简体中文版本

__add__ 与 __repr__ 重载运算符

定义 __add__ 让 + 号作用于自定义类、__repr__ 让实例打印可读;类型不符时返回 NotImplemented,解释器会抛出清晰的 TypeError 而不是 AttributeError。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

Vec2(4, 1)
Vec2(4, 6)
error: unsupported operand type(s) for +: 'Vec2' and 'int'

实现说明

真正干活的是类 Vec2和函数 __init__、__add__、__repr__,其余都是接线。

使用要点

  • 直接运行文件,输出会带上标签,比如 error:——输出的每一行都能指回产生它的那次调用。

常见问题

有需要管理的依赖吗?

没有。无需声明或安装任何依赖。 文件在加载时定义 __init__、__add__、__repr__。

主签名形如 def __init__(self, x, y)

核心语句

def __init__(self, x, y):
    self.x, self.y = x, y
def __add__(self, other):
    if not isinstance(other, Vec2):
        return NotImplemented
    return Vec2(self.x + other.x, self.y + other.y)
except TypeError as e:
    print("error:", e)

代码示例

class Vec2:
    def __init__(self, x, y):
        self.x, self.y = x, y

    # __add__ 让 + 号调用自定义加法
    def __add__(self, other):
        if not isinstance(other, Vec2):
            return NotImplemented
        return Vec2(self.x + other.x, self.y + other.y)

    def __repr__(self):
        return f"Vec2({self.x}, {self.y})"

a, b = Vec2(1, 2), Vec2(3, -1)
print(a + b)
print(a + b + Vec2(0, 5))
# 返回 NotImplemented 后解释器抛出清晰的 TypeError
try:
    a + 1
except TypeError as e:
    print("error:", e)