Zone Of Makos

Menu icon

Magic methods in Python

Magic methods, also known as special methods or dunder methods (short for "double underscore"), are a set of predefined methods in Python that allow you to define how objects of your classes behave in certain situations. Magic methods are always surrounded by double underscores, such as __init__ , __str__ , and __len__ . They are called automatically by the Python interpreter in response to certain events, such as object creation, attribute access, and arithmetic operations.

Creating magic methods

To create a magic method, you simply define a method with the appropriate name and parameters. The Python interpreter will automatically call the method when the corresponding event occurs. For example, to define a __len__ method for a custom class, you would write the following:


class MyClass:
    def __len__(self):
        return 42

my_object = MyClass()
print(len(my_object)) # Output: 42

Common magic methods

There are many magic methods available in Python, and they all have different purposes. Here are some of the most commonly used magic methods:

  • __init__(self, ...) : Called when the object is created, and used to initialize its attributes
  • __str__(self) : Called when the object is converted to a string, and used to define its string representation
  • __repr__(self) : Called when the object is converted to a string, and used to define its string representation for debugging
  • __len__(self) : Called when the built-in len() function is called on the object
  • __add__(self, other) : Called when the + operator is used to add two objects together
  • __eq__(self, other) : Called when the == operator is used to compare two objects for equality

Overriding built-in functions and operators

In addition to defining how your objects behave in certain situations, magic methods can also be used to override built-in functions and operators. For example, to make your custom class work with the + operator, you would define a __add__ method that returns the result of the addition.


class MyClass:
    def __init__(self, value):
        self.value = value
        
    def __add__(self, other):
        return MyClass(self.value + other.value)

a = MyClass(1)
b = MyClass(2)
c = a + b
print(c.value) # Output: 3

Conclusion

Magic methods play a crucial role in Python, allowing developers to customize and enhance the behavior of their classes. By implementing these methods, you can provide your objects with powerful functionality that integrates seamlessly with the built-in Python functions and operators. Some of the most commonly used magic methods in Python include `__str__`, `__repr__`, `__len__`, `__eq__`, `__lt__`, `__gt__`, and `__add__`. By mastering the use of these methods, you can take your Python programming skills to the next level and create more efficient and effective code. Keep in mind that while magic methods can be incredibly useful, it's important to use them appropriately and avoid overcomplicating your code.