Codzy

Advanced OOP: special methods and dataclasses

Special methods (or "dunder" methods, for double underscore) let your objects work with Python's operators: __add__ for +, __eq__ for ==, __len__ for len(), and __str__ to choose what print() shows.

The @dataclass decorator automatically writes __init__, __repr__ and __eq__ from the annotated attributes: ideal for classes that mostly store data. Finally, @classmethod and @staticmethod create methods tied to the class rather than to an object.

from dataclasses import dataclass

class Money:
    def __init__(self, amount):
        self.amount = amount

    def __add__(self, other):
        return Money(self.amount + other.amount)

    def __eq__(self, other):
        return self.amount == other.amount

    def __str__(self):
        return f"{self.amount} €"

print(Money(5) + Money(7))
print(Money(3) == Money(3))

@dataclass
class Point:
    x: int
    y: int

print(Point(1, 2))

Start the lesson