Where are operators mapped to magic methods in Python?

PythonServer Side ProgrammingProgramming

In this article, we will explain to you where are operators mapped to magic methods in python.

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.

Example

The following program lists all of the attributes and methods defined in the int class.

print(dir(int))

Output

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.

__add__ method

The __add__ method is a magic method that is invoked when we use the + operator to add two values. 1. Where are operators mapped to magic methods in Python?

Example

The following program returns the sum of a value to the given value using the __add__ method operator of the magic methods −

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))

Output

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 said, magic methods are not designed to be called directly, but rather indirectly, through other methods or actions.

In Python, magic methods are most commonly used to define overloaded behaviors of predefined operators. For example, arithmetic operators, by default, operate on numeric operands. This means that numeric objects must be used in conjunction with operators such as +, -, *, /, and so on. In the string, list, and tuple classes, the + operator is also specified as a concatenation operator. The + operator is said to be overloaded.

To make the overloaded behavior available in your own custom class, override the corresponding magic method. To use the + operator with objects of a user-defined class, for example, it must include the __add__() method.

__new__() method

To create a new instance of a class, languages such as Java and C# utilize the new operator. 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.

Example

# 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()

Output

On executing, the above program will generate the following output −

calling __new__ magic method
calling __init__ magic method

Here When you create an instance of the Tutorialspoint class, you will get the above result.

As a result, the __new__() method is called before the __init__() method.

__str__() method

__str__() is another important magic method. It is overridden to return a printable string representation of any user-defined class. We've already seen the built-in function str(), which returns a string from an object passed as a parameter.

Example

# 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))

Output

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.

And also the str() function internally calls the __str__() method defined in the class. Hence it is called a magic method!

Important Magic Methods

The tables below list the most significant magic methods in Python 3.

HeaInitialization & Constructionding 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.
Unary operators & functions Description
__pos__(self) To be called for unary positive ex: +someobject.
__neg__(self) To be called for unary negative ex: -someobject.
__abs__(self) To be called by built-in abs() function.
__invert__(self) To be called for inversion using the ~ operator.
__round__(self,n) To be called by built-in round() function.
__floor__(self) To be called by built-in math.floor() function.
__ceil__(self) To be called by built-in math.ceil() function.
__trunc__(self) To be called by built-in math.trunc() function.
Augmented Assignment Description
__iadd__(self, other) To be called on addition with assignment ex: a +=b.
__isub__(self, other) To be called on subtraction with assignment ex: a -=b.
__imul__(self, other) To be called on multiplication with assignment ex: a *=b.
__ifloordiv__(self, other) To be called on integer division with assignment ex: a //=b.
__idiv__(self, other) To be called on division with assignment ex: a /=b.
__itruediv__(self, other) To be called on true division with assignment
__imod__(self, other) To be called on modulo with assignment ex: a%=b.
__ipow__(self, other) To be called on exponents with assignment ex: a **=b.
__ilshift__(self, other) To get called on left bitwise shift with assignment ex: a<<=b.
__irshift__(self, other) To get called on right bitwise shift with assignment ex: a >>=b.
__iand__(self, other) To get called on bitwise AND with assignment ex: a&=b.
__ior__(self, other) To get called on bitwise OR with assignment ex: a|=b.
__ixor__(self, other) To get called on bitwise XOR with assignment ex: a ^=b.

Similarly, we have many other magic methods like Type Conversion Magic Methods, String Magic Methods, Attribute Magic Methods, Operator Magic Methods, etc − link

Conclusion

With examples, we learned about some of the operators that are mapped to magic methods in this article. In this article, we learned about magic methods and how they are used, as well as some of the operators of the magic methods.

raja
Updated on 09-Nov-2022 08:05:07

Advertisements