Dunder Methods
Dunder methods (ie double underscore methods) are methods that are called implicitly by python for instances of a class based on certain scenarios. These methods are not called manually by the programmer though and sometimes feel like magic (hence called magic methods)
One common example of a dunder method that is used often is the __init__
method that is used for initializing an object
class Square:
def __init__(self, side_length):
self.side_length = side_length
square = Square(1)
In the above code even though the __init__
method is not called it will be called implicity by python
Operator overloading with Dunder Methods
All python operators actually are implementing the dunder method internally. For example when we have code like value in array_variable
, the __contains__
dunder method is actually called
In other words calling value in array_variable
is the exact same as value.__contains__(array_variable)
So operator overloading is as easy as just implementing the dunder methods. There are many dunder methods like __str__
, __repr__
, __new__
etc
Using __repr__ vs __str__
__repr__
and __str__
are two dunder methods that are used to display information about the class to a human. Use __repr__
to print detailed information about a class to the developer / programmer and use __str__
to print basic information about the class to an end user.
Ideally the output of a __repr__
can be directly run in the python repl to create an object