Metodele dunder ("double underscore," numite și metode magic/special) sunt metode cu nume speciale precum __init__, __str__, __len__ care permit obiectelor tale să se integreze cu operatorii și funcțiile integrate ale Python. Python le apelează automat în răspuns la sintaxă — de exemplu, len(obj) apelează obj.__len__().
Facând obiectele să se comporte ca tipurile integrate
class Vector:
def __init__(self, x, y): # constructor — Vector(1, 2)
self.x, self.y = x, y
def __repr__(self): # repr(v) and the REPL — for developers
return f"Vector({self.x}, {self.y})"
def __str__(self): # str(v) / print(v) — for users
return f"({self.x}, {self.y})"
def __add__(self, other): # enables the + operator: v1 + v2
return Vector(self.x + other.x, self.y + other.y)
def __eq__(self, other): # enables ==
return self.x == other.x and self.y == other.y
v1, v2 = Vector(1, 2), Vector(3, 4)
v1 + v2 # Vector(4, 6) — calls __add__
print(v1) # (1, 2) — calls __str__
v1 == Vector(1, 2) # True — calls __eq__
Definind acestea, obiectele tale personalizate funcționează cu sintaxa nativă (+, ==, print) exact ca și tipurile integrate.
Metode dunder obișnuite
__init__ → constructor (object creation)
__repr__ → unambiguous developer representation (debugging, REPL)
__str__ → readable user-facing string (print, str())
__len__ → len(obj)
__getitem__→ obj[key] (indexing/subscripting)
__iter__ / __next__ → make an object iterable (for loops)
__eq__, __lt__, __gt__ → comparison operators (==, <, >)
__add__, __sub__, __mul__ → arithmetic operators
__call__ → make an instance callable like a function: obj()
__contains__ → the `in` operator
__enter__ / __exit__ → context managers (with statement)
Exemplu: facând un obiect iterabil și indexabil
class Deck:
def __init__(self): self.cards = [...]
def __len__(self): return len(self.cards) # len(deck)
def __getitem__(self, i): return self.cards[i] # deck[0], and iteration/slicing!
deck = Deck()
len(deck) # works
for card in deck: # __getitem__ makes it iterable too
...
Implementarea __len__ și __getitem__ face ca obiectul să se comporte ca o secvență — suportând len(), indexare, iterație și slicing.
De ce conteaza
Metodele dunder sunt cum Python realizează sentimentul său consistent, "totul este un obiect" — ele permit claselor tale personalizate să se integreze fără probleme cu operatorii și funcțiile integrate ale limbajului (+, ==, len(), for, [], with, print).
Aceasta este baza designului elegant și polimorf al Python ("duck typing" + modelul de date).
Cunoscând metodele dunder cheie — în special __init__, __repr__/__str__, operatorii de comparație și aritmetici, și protocolul de iterație — îți permite să construiești clase intuitive, pythonic care se simt ca tipuri native, și explică cum sintaxa limbajului se mapează la apelurile de metode sub capot.
