Home » Learn Python » Dunder (Magic) Methods » What Are Dunder Methods?

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 be converted to strings, or implement __add__ to enable objects to be added together.

We can obtain a list of all the methods and attributes of a class using the dir() builtin function. In this code we use it on the str class, and you can see that many dunder methods have been implemented.

['__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', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

Leave a Reply

Blog at WordPress.com.