Dunder methods ("double underscore," uga diarani magic/special methods) yaiku methods sing dhuwur-asma kayata __init__, __str__, sing lumikua obyek mu bisa nglakoni karo . Python njaluk saben ana syntax — contone njaluk .
__len__len(obj)obj.__len__()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__
Dhefinisi iki nggawe obyek kamu bisa nganggo native syntax (+, ==, print) kayata built-in types.
__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)
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
...
Nggawe __len__ lan __getitem__ nggawe obyek padha sequence — ngedukung len(), indexing, iteration, lan slicing.
Dunder methods yaiku carane Python nggayuh "everything is an object" — silo obyek mu bisa nglakoni karo operator lan built-in function (+, ==, len(), for, [], with, print).
Iki dadi fondasi saka Python elegant, polymorphic design ("duck typing" + data model).
Karun key dunders — utamane __init__, __repr__/__str__, comparison lan arithmetic operators, lan iteration protocol — mudhun obyek mu sing intuitif, Pythonic, lan padha native types, lan nerangake carane syntax Python mapan method calls ing ngisor pasuryan.