Magic Methods in Python
Magic Methods?? They’re not magic at all, just pretty useful when used correctly. This article emphasis on some of the magic methods used in Python.
Here’s a list of some common magic methods that exist-
__init__ is the initialize of the class and is analogous to the constructor in Java and other languages. It’s the second method to be called in the lifecycle of a class; after __new__ has finished its execution. We won’t be covering __new__ as it’s very rarely used and most people manage to get around their jobs in complete ignorance of the method. The first argument ‘self’ refers to the current instance of the class.
Execution of the following code gives us ‘a’ as the output in the interpreter. We’ve successfully used the __init__ method to add to a property to our class object.
This method is a comparison type magic method. It is used to define the behavior of the equality operator ‘==’ for two objects of the same class.
This method is a comparison type magic method. It is used to define the behavior of the equality operator ‘!=’ for two objects of the same class.
Similarly, __lt__, __gt__, __le__, __ge__ define the operations for ‘<’, ’>’, ’<=’, ’>=’ operators.
Understandably, the above script gets us the following output.
“False checking less than by definition in __lt__ True”
This allows you to define the behavior when a user tries to access an attribute that does not exist. This method does not get called for any attribute that exists.
__setattr__(self, name, value)
This method is executed for every attempt to set an attribute value regardless of the attribute’s existence in the class object.
This method is executed when str() is called on the instance of the class. It is also called whenever an attempt to print the value of the class is made.
__doc__ is a subtle way of attaching documentation to methods, functions, and classes. __doc__ returns a string constant when it is the first statement inside the object definition.
__doc__ is not a method. Still magic though.
For the following example, an attempt to print an object of class A returns ‘My value is <value>’.
__doc__ gives us ‘This is example documentation’.
Well, this is it for this article. Hope, you have an idea about How to use Magic Methods in Python. I will appreciate your queries and feedbacks in the comment section. Until then, keep coding!