Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Where are operators mapped to magic methods in Python?
In this article, we will explain where operators are mapped to magic methods in Python and how they enable operator overloading.
Python Magic methods are special methods that begin and end with double underscores. They are also known as dunder methods. Magic methods are not intended to be invoked directly by you, but rather invocation occurs by the class on a specific action. When you use the + operator to add two numbers, the __add__() method is called internally.
Many magic methods in Python are defined by built-in classes. To get the number of magic methods inherited by a class, use the dir() function ?
Exploring Magic Methods with dir()
The following program lists all of the attributes and methods defined in the int class ?
print(dir(int))
On executing, the above program will generate the following output ?
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
Here the int class contains a number of magic methods surrounded by double underscores.
The __add__() Method
The __add__ method is a magic method that is invoked when we use the + operator to add two values ?
n = 20
# adding 10 to input number using + sign
print("Addition using + sign:", n + 10)
# adding 10 to input number using __add__ method
# by passing the value to be added as an argument
print("Addition using __add__ method:", n.__add__(10))
On executing, the above program will generate the following output ?
Addition using + sign: 30 Addition using __add__ method: 30
As you can observe, the + operator invokes the __add__(10) method when you enter n+10. You may alternatively explicitly call n.__add__(10) to get the same result. However, as previously stated, magic methods are not designed to be called directly, but rather indirectly, through other methods or actions.
The __new__() Method
The __new__() magic method is called implicitly before the __init__() method in Python. The __new__() method returns a new object, which is subsequently initialized using the __init__() method ?
# defining a class
class Tutorialspoint:
def __new__(democlass):
print("calling __new__ magic method")
instance = object.__new__(democlass)
return instance
def __init__(self):
print("calling __init__ magic method")
self.author = 'XYZ'
# calling the above-defined Tutorialspoint class
result = Tutorialspoint()
On executing, the above program will generate the following output ?
calling __new__ magic method calling __init__ magic method
When you create an instance of the Tutorialspoint class, the __new__() method is called before the __init__() method.
The __str__() Method
__str__() is another important magic method. It is overridden to return a printable string representation of any user-defined class. The built-in function str() internally calls this method ?
# input number n = 10 # printing the string form of a number using str() print(str(n)) # printing the string form of a number using __str__() magic method # Both are equivalent print(int.__str__(n))
On executing, the above program will generate the following output ?
10 10
Here str(10) returns the value '10'. When called, it invokes the int class's __str__() method. The str() function internally calls the __str__() method defined in the class.
Common Operator-to-Magic Method Mappings
| Initialization & Construction | Description |
|---|---|
| __new__(cls, other) | To be called at the instantiation of an object. |
| __init__(self, other) | To get called by the __new__ method. |
| __del__(self) | Destructor method. |
| Arithmetic Operators | Magic Method |
|---|---|
| + | __add__(self, other) |
| - | __sub__(self, other) |
| * | __mul__(self, other) |
| / | __truediv__(self, other) |
| // | __floordiv__(self, other) |
| % | __mod__(self, other) |
| ** | __pow__(self, other) |
| Comparison Operators | Magic Method |
|---|---|
| == | __eq__(self, other) |
| != | __ne__(self, other) |
| < | __lt__(self, other) |
| > | __gt__(self, other) |
| <= | __le__(self, other) |
| >= | __ge__(self, other) |
Conclusion
Magic methods in Python provide the mapping between operators and their underlying implementations. Understanding these mappings allows you to implement operator overloading in custom classes and leverage Python's intuitive syntax for your own objects.
