Dunder (Magic) Methods
-
Subclassing Dictionaries
There are many possible uses for dunder methods in Python. Most of the things you can do with objects can be implemented or altered using dunder methods. Here’s an interesting example. By default, dictionary objects throw an error if you try to retrieve a value that doesn’t exist in the dictionary. A common way to…
-
Comparing Objects
If you want it to be possible to compare your objects using ==, you can implement __eq__ The default implementation will only tell you if two variables refer to the same object, but by implementing __eq__ you can make it possible to check if two objects are equal semantically: in terms of their programmer-defined meaning.…
-
Adding Objects
You can implement the __add__ dunder method to make it possible to add objects together. Consider the addition operator, +. We can think of this as being like a function that accepts two arguments: the two things to be added together. It returns a new object of the same type as the objects being added.…
-
Converting Objects to Strings
You can make it possible to obtain a string representation of your objects by implementing the __str__ method in your classes. This method must return a string representation of your object. The __repr__ Method The purpose of __str__ is to return a human-readable “informal” representation of an object. You can tweak it as necessary, to…
-
What Are Dunder Methods?
Python objects have special kinds of methods called dunder methods, or magic methods. These methods have names that start and end with a double underscore. “Double underscore” is shortened to “dunder”, hence the name. You can implement these methods to add additional special functionality to your objects. For example, implement __str__ to enable objects to…