__add__ And __repr__ Overload Operators
Teach the + operator to work on your class by defining __add__, and make instances print readably with __repr__, returning NotImplemented for wrong types.
Code
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)Output
Captured from a sandboxed run of this snippet in the build pipeline.
Vec2(4, 1)
Vec2(4, 6)
error: unsupported operand type(s) for +: 'Vec2' and 'int'How it works
The snippet is organized around the class Vec2 and the functions __init__, __add__ and __repr__.
What to watch for
- Runs on the standard library alone; nothing to install.
Using it
The entry-point signature is def __init__(self, x, y)
The file’s steps show up in the output as error:.
Key statements
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)
Interactive Tools for This Topic
FAQ
- Are there dependencies to manage?
- No. There are no dependencies to declare or install. The file defines `__init__`, `__add__`, `__repr__` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.