Skip to content
Python

Magic Methods

Common magic method examples.

By EZ4Code Team
magicdunder

Code

class Vector:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __repr__(self):
        return f"Vector({self.x}, {self.y})"

    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)

    def __eq__(self, other):
        return self.x == other.x and self.y == other.y

    def __len__(self):
        return 2

    def __getitem__(self, i):
        return (self.x, self.y)[i]

    def __iter__(self):
        yield self.x
        yield self.y

Explanation

Magic methods implement operator, iteration, comparison, and other behaviors for objects.

More Python Snippets