Python has a set of magic methods that can be used to enrich data classes; they are special in the way they are invoked. These methods are also called “dunder methods” because they start and end with double underscores. Dunder methods allow developers to emulate built-in methods, and it’s also how operator overloading is implemented in Python. For example, when we add two integers together, 4 + 2, and when we add two strings together, “machine” + “learning”, the behaviour is different. The strings get concatenated while the integers are actually added together.

The “Essential” Dunder Methods

If you have ever created a class of your own, you already know one of the dunder methods, __init__(). Although it’s often referred to as the constructor, it’s not the real constructor; the __new__() method is the constructor. The superclass’s  __new__() , super().__new__(cls[, ...]), method is invoked, which creates an instance of the class, which is then passed to the __init__() along with other arguments. Why go through the ordeal of creating the __new__() method? You don’t need to; the __new__() method was created mainly to facilitate the creation of subclasses of immutable types (such as int, str, list) and metaclasses.

#developers corner #uncategorized #dunder methods #magic methods #operator overriding #python dunder methods #python magic methods

Comprehensive Guide To Python Dunder Methods
1.45 GEEK