Dunder or magic methods in Python are the methods having two prefix and suffix underscores in the method name. Dunder here means “Double Under (Underscores)”. These are commonly used for operator overloading. Few examples for magic methods are:
__init__, __add__, __len__, __repr__ etc.
__init__ method for initialization is invoked without any call, when an instance of a class is created, like constructors in certain other programming languages such as C++, Java, C#, PHP etc. These methods are the reason we can add two strings with ‘+’ operator without any explicit typecasting.
Here’s a simple implementation :
<__main__.String object at 0x7fe992215390>
The above snippet of code prints only the memory address of the string object. Let’s add a
__repr__ method to represent our object.
If we try to add a string to it :
TypeError: unsupported operand type(s) for +: 'String' and 'str'
__add__ method to String class :
Reference : docs.python.org.
- Customize your Python class with Magic or Dunder methods
- Python | Implementing 3D Vectors using dunder methods
- Python String Methods | Set 1 (find, rfind, startwith, endwith, islower, isupper, lower, upper, swapcase & title)
- Python String Methods | Set 2 (len, count, center, ljust, rjust, isalpha, isalnum, isspace & join)
- Python String Methods | Set 3 (strip, lstrip, rstrip, min, max, maketrans, translate, replace & expandtabs())
- List Methods in Python | Set 1 (in, not in, len(), min(), max()...)
- List Methods in Python | Set 2 (del, remove(), sort(), insert(), pop(), extend()...)
- Dictionary Methods in Python | Set 1 (cmp(), len(), items()...)
- Dictionary Methods in Python | Set 2 (update(), has_key(), fromkeys()...)
- List methods in Python
- Analysis of Different Methods to find Prime Number in Python
- Accessing Attributes and Methods in Python
- Python | Float type and its methods
- Private Methods in Python
- Bound methods python
- Bound, unbound, and static methods in Python
- Http Request methods - Python requests
- Response Methods - Python requests
- Accessor and Mutator methods in Python
- Element methods in Selenium Python
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.