Dunder Methods
Short for "Double Underscore", a.k.a., Magic Methods, these are special methods that allow your custom classes to
"hook" into Python's built-in behaviors, such as arithmetic, comparisons, or string formatting.
-
String Representation
:
Defines how an object 'presents' itself as a string, ensuring it is easily-readable for users __str__
and debugging-friendly for developers __repr__.
-
Arithmetic Operations
:
Operator overloading via __add__ (+), __sub__ (-), and __mul__ (*), etc.,
allowing custom objects work with standard mathematical syntax, making them behave like built-in numeric types.
-
Container & Sequence Protocol
:
Allowing collection behavior via __len__ (length) and __getitem__ (indexing), such that
your class can be treated like a list or dictionary, allowing them to be indexed, sliced, or measured.
-
Lifecycle & Callable
:
Enabling construction & execution, like __init__ initializes an instance, __new__ (a
magic class method) handles the memory allocation and returns the object (often used in Singleton),
__call__ allows an instance to be executed like a function.
-
Comparison Methods
:
Allowing custom logic for standard operators like ==, <, >, enabling
objects to be sorted or filtered based on specific attributes.