Dunder Functions in Python
Dunder functions (also called magic methods) are special methods in Python that start and end with
double underscores (__).
They enable customization of object behavior, operator overloading, and more.
Some common dunder functions:
1. Object Initialization & Representation
- __init__(self, ...) : Constructor method for initializing an instance.
- __str__(self) : Returns a user-friendly string representation.
- __repr__(self) : Returns an unambiguous string representation.
2. Operator Overloading
- __add__(self, other) : Defines + (addition).
- __sub__(self, other) : Defines - (subtraction).
- __mul__(self, other) : Defines * (multiplication).
- __truediv__(self, other) : Defines / (division).
3. Comparison Operators
- __eq__(self, other) : Defines == (equality).
- __lt__(self, other) : Defines < (less than).
4. Container & Iteration Behavior
- __len__(self) : Defines len(obj).
- __getitem__(self, key) : Defines indexing (obj[key]).
5. Callable Objects
- __call__(self, *args) : Makes an object callable like a function (obj()).
6. Context Managers
- __enter__(self) : Setup for a 'with' statement.
- __exit__(self, exc_type, exc_value, traceback) : Cleanup for 'with'.
Python Code Example
class DunderExample:
def __init__(self, value):
self.value = value
def __str__(self):
return f"DunderExample({self.value})"
def __add__(self, other):
return DunderExample(self.value + other.value)
a = DunderExample(10)
b = DunderExample(20)
print(a + b) # Uses __add__