Skip to content
UPEEC

Dunder Methods

Special __methods__ let your objects work with built-in syntax like +, len() and print().

Intermediate
Comments 0
class Vector:
    def __init__(self, x, y):
        self.x, self.y = x, 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})"
    def __len__(self):
        return 2

Others: __eq__, __lt__ (comparisons), __iter__ (for loops), __enter__/__exit__ (with statements). The @dataclass decorator writes __init__, __repr__ and __eq__ for you.

Spotted a mistake or want to add detail? Suggest an improvement — Content Contributors' edits are reviewed by editors before they go live.

Discussion (0)

Sign in or join free to ask questions and discuss this topic.