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 avoid this is to import defaultdict class from the collections package and use that instead, but an alternative is to implement the __missing__ method in a subclass of dict.
In this program we create a dict of names vs. ages. We implement __missing__ so that if a name is requested that is not a key in the dictionary, instead of raising an error, the dict returns the value 0 and prints a warning.
class NameAge(dict):
def __missing__(self, name):
print(f"{name} not found")
return 0
names = NameAge({"Joe": 20, "Emily": 24})
print("Joe", names["Joe"])
print("Emily", names["Emily"])
print("Bob", names["Bob"])
Joe 20
Emily 24
Bob not found
Bob 0
Leave a Reply