Special (Magic/Dunder) methods in python

Magic methods in Python are the special methods which add “magic” to your class. Their name have two underscores as prefix and suffix. They are also called as Dunder methods. Dunder here is simply a creative short name for these “double underscores” methods.

Here are a few examples for magic methods: __init__, __add__, __len__, __str__ etc.

You don’t need to call these methods directly as you do for other methods: Python calls them for you when it needs to know how you want some specific things (object initialization, representation, etc) should be handled.

Let’s take a look on below example:

class Book():
    def __init__(self, title, author, pages):
        self.title = title
        self.author = author
        self.pages = pages

b = Book('Python Magic methods', 'Andy', 100)
print(b)
# <__main__.Book object at 0x7fe948549080>

str(b)
# <__main__.Book object at 0x7fe948549080>

len(b)
TypeError                                 Traceback (most recent call last)
<ipython-input-14-97d8916a185b> in <module>
----> 1 len(b)

TypeError: object of type 'Book' has no len()

First, The __init__(self) is also a magic method, it initializes the object and is invoked without any call, when an instance of a class is created, like constructors in certain other programming languages such as C++, Java etc.

And as you see, by default , print() and str() statement of an Object return the Object location itself in memory. Or len(b) will get Type Error when called.

Now let’s add some more magic methods to the Book.

class Book():
    def __init__(self, title, author, pages):
        self.title = title
        self.author = author
        self.pages = pages

    def __str__(self):
        return self.__class__.__name__ + ': ' +  self.title.capitalize() + ' By ' + self.author.capitalize()

b = Book('Python Magic methods', 'Andy', 100)
print(b)
# Book: Python magic methods By Andy
str(b)
# 'Book: Python magic methods By Andy'
len(b)
# 100

Built-in classes in Python define many magic methods. Use the dir() function to see the number of magic methods inherited by a class. For example, the following lists all the attributes and methods defined in the strclass.

>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

Reference:

https://www.tutorialsteacher.com/python/magic-methods-in-python

Leave a comment