Magic Methods In Python
Magic methods in Python are the special methods that start and end with the double underscores. They are also called Dunder methods, Dunder here means “Double Under (Underscores)”. These are commonly used for operator overloading.
Some examples of magic methods are __init__, __len__, __repr__, __add__, and etc.
__init__
The __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.
Example :
Output :
<__main__.String object at 0x7fe992215390>__repr__
Python __repr__method returns the object representation in string format.
In above snippet of code it prints only the memory address of the string object. Let’s add a __repr__ method to represent our object.
Example :
Output :
Hello__len__
The Python __len__ method returns a positive integer that represents the length of the object on which it is called. It implements the built-in len() function.
Get Krutik Jain’s stories in your inbox
Join Medium for free to get updates from this writer.
Example :
Output :
3__ contains __
Python __ contains __ is a method of the String class in Python. It can check whether a given substring is part of a string or not.
Example :
Output :
True__setitem__ & __getitem__
__setitem__ is a method used for assigning a value to an item. It is implicitly invoked when we set a value to an item of a list, dictionary, etc.
__getitem__ is a method used for getting the value of an item. It is implicitly invoked when we access the items of a list, dictionary, etc.
Example :
Output :
bob
42Conclusion :
So, this was all about Python’s magic methods’ world. I hope this piece of writing was informative & helpful.
All Code Can be Found Here.
Thank you.




![Flutter and Blockchain — Flutter Dapp [2023]](https://miro.medium.com/v2/resize:fit:1358/format:webp/1*SPOxevn7DO64N1w6Kq3hOw.png)




