实现说明
真正干活的是类 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)