At times, while coding in Python to create programs and games and whatever else your passion is in using Python, you must have wondered what goes on behind operator symbols. It cannot be plain and simple that you put an operator to add or subtract or multiply integers and the Computer understand the logic behind it. There must be some class definition or function that allows itself to compile whenever these operators are called. You are correct, and here enters the wonderful concept in Python, ‘Magic Functions’ or some call them ‘Dunder Methods’.
What are Magic or Dunder Methods?
Python magic methods are special methods that allow you to define how objects of your class behave when certain operations are performed on them. They are important because they allow you to customize the behavior of your objects and make your code more readable.
Python’s magic methods – also known as dunder (double underscore) methods – can be used to implement a lot of cool things. Most of the time we use them for simple stuff, such as constructors (init), string representation (str, repr), or arithmetic operators (add / mul). But they can be used for much more than that. They’re everything in object-oriented Python. These are special methods that you can define to add “magic” to your classes. They’re always surrounded by double underscores (e.g. __init__or lt)
How to use Magic or Dunder Methods in Python?
Python magic methods can be used by defining them in the class definition. When an object of a defined class is used in a certain way (such as being added to another object), Python will automatically call the appropriate magic method.
Here’s an example of how you can use magic methods in Python:
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def __str__(self):
return f"{self.name} earns {self.salary}"
def __add__(self, other):
return self.salary + other.salary
emp1 = Employee("John", 5000)
emp2 = Employee("Mary", 6000)
print(emp1 + emp2) # Output: 11000
In this example, we have defined a class called Employee with two attributes – name and salary. We have also defined three magic methods – init, str, and add. The init method is used to initialize the object with values for name and salary. The str method is used to return a string representation of the object when it is printed. The add method is used to overload the + operator so that it can be used to add two Employee objects together.
What are the best practices to use Magic or Dunder Methods?
Here are some best practices when using magic methods in Python:
- Use magic methods sparingly: Magic methods can be very powerful, but they can also make your code harder to read and understand if overused. Use them only when necessary.
- Follow naming conventions: Magic methods have a specific naming convention that you should follow. They always start and end with double underscores (e.g. init or str). Following this convention makes your code more readable and easier to understand.
- Document your code: Magic methods can be confusing for other developers who are not familiar with your code. Make sure to document your code well so that others can understand what you’re doing.
- Be careful with operator overloading: Operator overloading can be very useful, but it can also make your code harder to read and understand if overused. Use it only when necessary.
- Don’t use magic methods for everything: Magic methods are not a silver bullet for all your programming problems. Use them only when they make sense and when they improve the readability of your code.
List of Magic or Dunder Methods in Python
Following is the complete list of magic methods or dunder methods in Python:
Initialization and Construction | Description |
__new__(cls, other) | This method is called when an instance of a class is created and returns a new instance of the class. |
__init__(self, other) | This method is called after an instance has been created and initializes the instance’s attributes. |
__del__(self) | Destructor method is called when an instance is about to be destroyed and performs any necessary cleanup. |
Unary operators and functions | Description |
__pos__(self) | This method is called when the unary plus operator (+) is used with an object. |
__neg__(self) | This method is called when the unary minus operator (-) is used with an object. |
__abs__(self) | This method is called when the built-in abs() function is used with an object. |
__invert__(self) | This method is called when the bitwise NOT operator (~) is used with an object. |
__round__(self,n) | This method is called when the built-in round() function is used with an object. |
__floor__(self) | This method is called when the built-in math.floor() function is used with an object. |
__ceil__(self) | This method is called when the built-in math.ceil() function is used with an object. |
__trunc__(self) | This method is called when the built-in math.trunc() function is used with an object. |
Augmented Assignment | Description |
__iadd__(self, other) | This method is called when there is addition with assignment e.g. a +=b. |
__isub__(self, other) | This method is called when there is subtraction with assignment e.g. a -=b. |
__imul__(self, other) | This method is called when there is multiplication with assignment e.g. a *=b. |
__ifloordiv__(self, other) | This method is called when there is integer division with assignment e.g. a //=b. |
__idiv__(self, other) | This method is called when there is division with assignment e.g. a /=b. |
__itruediv__(self, other) | This method is called when there is true division with assignment |
__imod__(self, other) | This method is called when there is modulo with assignment e.g. a%=b. |
__ipow__(self, other) | This method is called when there is exponentswith assignment e.g. a **=b. |
__ilshift__(self, other) | This method is called when there is left bitwise shift with assignment e.g. a<<=b. |
__irshift__(self, other) | This method is called when there is right bitwise shift with assignment e.g. a >>=b. |
__iand__(self, other) | This method is called when there is bitwise AND with assignment e.g. a&=b. |
__ior__(self, other) | This method is called when there is bitwise OR with assignment e.g. a|=b. |
__ixor__(self, other) | This method is called when there is bitwise XOR with assignment e.g. a ^=b. |
Type Conversion Magic Methods | Description |
__int__(self) | This method is called when the built-in int() method is used to convert a type to an int. |
__float__(self) | This method is called when the built-in float() method is used to convert a type to float. |
__complex__(self) | This method is called when the built-in complex() method is used to convert a type to complex. |
__oct__(self) | This method is called when the built-in oct() method is used to convert a type to octal. |
__hex__(self) | This method is called when the built-in hex() method is used to convert a type to hexadecimal. |
__index__(self) | This method is called on type conversion to an int when the object is used in a slice expression. |
String Magic Methods | Description |
__str__(self) | This method is called when the built-in str() method is used to return a string representation of a type. |
__repr__(self) | This method is called when the built-in repr() method is used to return a machine readable representation of a type. |
__unicode__(self) | This method is called when the built-in unicode() method is used to return an unicode string of a type. |
__format__(self, formatstr) | This method is called when the built-in string.format() method is used to return a new style of string. |
__hash__(self) | This method is called when the built-in hash() method is used to return an integer. |
__nonzero__(self) | This method is called when the built-in bool() method is used to return True or False. |
__dir__(self) | This method is called when the built-in dir() method is used to return a list of attributes of a class. |
__sizeof__(self) | This method is called when the built-in sys.getsizeof() method is used to return the size of an object. |
Attribute Magic Methods | Description |
__getattr__(self, name) | This method is called when the accessing attribute of a class that does not exist. |
__setattr__(self, name, value) | This method is called when assigning a value to the attribute of a class. |
__delattr__(self, name) | This method is called when deleting an attribute of a class. |
Operator Magic Methods | Description |
__add__(self, other) | This method is called for add operation using + operator |
__sub__(self, other) | This method is called for subtraction operation using – operator. |
__mul__(self, other) | This method is called for multiplication operation using * operator. |
__floordiv__(self, other) | This method is called for floor division operation using // operator. |
__truediv__(self, other) | This method is called for division operation using / operator. |
__mod__(self, other) | This method is called for modulo operation using % operator. |
__pow__(self, other[, modulo]) | This method is called for calculating the power using ** operator. |
__lt__(self, other) | This method is called for comparison using < operator. |
__le__(self, other) | This method is called for comparison using <= operator. |
__eq__(self, other) | This method is called for comparison using == operator. |
__ne__(self, other) | This method is called for comparison using != operator. |
__ge__(self, other) | This method is called for comparison using >= operator. |
More to Read:
- Section 3.3. Special method names (Python Documentation)
Please, don’t forget to subscribe newsletter for updates on new articles and upcoming exciting sections.