Magic methods (also known as dunder methods) are special methods in Python that start and end with double underscores (__method__
). They enable the customization of built-in behaviors such as object construction, representation, comparison, and arithmetic operations.
- Defined using double underscores (e.g.,
__init__
,__str__
,__add__
) - Automatically invoked by Python in specific operations
- Used to define operator overloading, object lifecycle, and more
- Common magic methods like
__init__
,__str__
,__repr__
- Operator overloading using methods like
__add__
,__sub__
,__eq__
- Object comparison with
__lt__
,__gt__
,__eq__
, etc. - Customizing object behavior using
__len__
,__getitem__
,__call__