Codzy

OOP avanzata: metodi speciali e dataclass

I metodi speciali (o «dunder», da double underscore) permettono ai tuoi oggetti di funzionare con gli operatori di Python: __add__ per +, __eq__ per ==, __len__ per len() e __str__ per scegliere che cosa mostra print().

Il decoratore @dataclass scrive automaticamente __init__, __repr__ ed __eq__ a partire dagli attributi annotati: ideale per le classi che servono soprattutto a conservare dati. Infine, @classmethod e @staticmethod creano metodi legati alla classe invece che a un oggetto.

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))

Inizia la lezione