Data Model
Operator Overloading
__add__ defines how the + operator combines two objects.
Source
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __repr__(self):
return f"Vector({self.x}, {self.y})"
print(Vector(2, 3) + Vector(4, 5))Output
Vector(6, 8)__eq__ defines value equality for ==. Without it, user-defined objects compare by identity.
Source
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return (self.x, self.y) == (other.x, other.y)
print(Vector(1, 1) == Vector(1, 1))Output
TrueA useful __repr__ makes operator results inspectable while debugging.
Source
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __repr__(self):
return f"Vector({self.x}, {self.y})"
print(repr(Vector(2, 3) + Vector(4, 5)))Output
Vector(6, 8)Notes
- Overload operators only when the operation is unsurprising.
- Return
NotImplementedwhen an operand type is unsupported. - Implement equality deliberately when value comparison matters.
See also
- prerequisite: Operators
- related: Special Methods
- related: Equality and Identity
Run the complete example
Expected output
Vector(6, 8)
True
Execution time appears here after you run the example.