Dunder Functions
Dunder Functions
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.
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).
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'.
class DunderExample:
def __init__(self, value):
self.value = value
def __str__(self):
return f"DunderExample({self.value})"
a = DunderExample(10)
b = DunderExample(20)
print(a + b) # Uses __add__