Data Model

Operator Overloading

Operator methods let objects define arithmetic and comparison syntax.

__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)
a + bdispatchesa.__add__(b)
Defining `__add__` on a class lets `+` dispatch into the class's own behavior.

__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

True

A 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

See also

Run the complete example

Example code

Expected output

Vector(6, 8)
True

Execution time appears here after you run the example.