Operator Magic Methods
In Python, methods starting and ending with double underscores '__' are called Magic methods or Dunder methods (Double Under). These methods are widely used for operator overloading. [1]
Operator Overloading
Here is the table of the most common operator megic methods in Python (self and x refer to the same object):
| Method Definition | Operator | Description |
|---|---|---|
__add__(self, y) | x + y | The addition of two objects. The type of x determines which add operator is called. |
__contains__(self, y) | y in x | When x is a collection you can test to see if y is in it. |
__call__(self, x, y) | object(x, y) | The class instance (object )will behave like a function which can be called. |
__eq__(self, y) | x == y | Returns True or False depending on the values of x and y. |
__ge__(self,y) | x >= y | Returns True or False depending on the values of x and y. |
__getitem__(self,y) | x[y] | Returns the item at the y-th position in x. |
__gt__(self,y) | x > y | Returns True or False depending on the values of x and y. |
__hash__(self) | hash(x) | Returns an integral value for x. |
__int__(self) | int(x) | Returns an integer representation of x. |
__iter__(self) | for v in x | Returns an iterator object for the sequence x. |
__le__(self,y) | x <= y | Returns True or False depending on the values of x and y. |
__len__(self) | len(x) | Returns the size of x where x has some length attribute. |
__mod__(self,y) | x%y | Returns the value of x modulo y. This is the remainder of x/y. |
__mul__(self,y) | x*y | Returns the product of x and y. |
__ne__(self,y) | x != y | Returns True or False depending on the values of x and y. |
__neg__(self) | -x | Returns the unary negation of x. |
__repr__(self) | repr(x) | Returns a string version of x suitable to be evaluated by the eval function. |
__setitem__(self,i,y) | x[i] = y | Sets the item at the i-th position in x to y. |
__str__(self) | str(x) | Return a string representation of x suitable for user-level interaction. |
__sub__(self,y) | x - y | The difference of two objects. |
Table 1: Python Operator Magic Methods [2].
References
- [1] Dunder or magic methods in Python (https://www.geeksforgeeks.org/dunder-magic-methods-python/)
- [2] Lee, Kent D., and Steve Hubbard. Data structures and algorithms with python. Second Edition, Springer Nature Switzerland AG 2024.
Changelog
- Dec 24, 2024: Add
__call__megic method.