"Dunder" methods (short for "double underscore" methods) are special methods in Python that begin and end with double underscores (__), like __init__, __str__, and __len__. They’re also known as magic methods or special methods.
These methods are used to:
-
Customize the behavior of built-in operations
-
Enable operator overloading
-
Integrate your class with Python's core language features (like iteration, context managers, etc.)
✅ Example:
-
__init__: Initializes the object (like a constructor). -
__str__: Defines whatstr(obj)orprint(obj)returns.
🧠Common Dunder Methods:
| Method | Purpose |
|---|---|
__init__ | Constructor (called on object creation) |
__str__ | String representation (print(obj)) |
__repr__ | Debug representation (repr(obj)) |
__len__ | Length (len(obj)) |
__getitem__ | Indexing (obj[i]) |
__iter__ | Makes an object iterable |
__eq__ | Equality (==) |
Dunder methods let your objects behave like built-in types and integrate seamlessly with Python’s syntax and idioms.

No comments:
Post a Comment