python
  1. python-magic-methods

Python Magic Methods

Magic methods or dunder methods are special methods in Python that start and end with double underscores.

Magic methods are used to define how objects of a class behave with respect to operators and built-in functions. These methods help us in operator overloading and create features similar to built-in types.

Syntax

The syntax of magic methods in Python is as follows:

__magic_method__(self, ...parameters)

Here,

  • __magic_method__ - represents the name of the magic method.
  • self - represents the object instance.
  • ...parameters - represents the parameters for the magic method.

Example

Let's consider the following example that demonstrates the usage of Python magic methods:

class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def __str__(self):
        return f"Rectangle({self.width}, {self.height})"

    def __add__(self, other):
        return Rectangle(self.width + other.width, self.height + other.height)

r1 = Rectangle(10, 20)
r2 = Rectangle(5, 15)
print(r1 + r2)  # Output: Rectangle(15, 35)

In the above example, we have defined a Rectangle class and implemented the __init__, __str__, and __add__ magic methods.

  • __init__ method is called when an instance of the Rectangle class is created.
  • __str__ method is called when an instance of the Rectangle class is converted to a string.
  • __add__ method is called when two instances of the Rectangle class are added together.

Explanation

  • __init__(self, ...parameters) - This method is called when the class is initialized. It takes the object instance as the first argument, followed by any number of additional arguments that are specified during initialization of the class instance.
  • __str__(self) - This method is called to convert the object instance to a string.
  • __add__(self, other) - This method is called to define the behavior of the + operator when applied to two instances of a class.

Use

Magic methods are used to define custom behavior of operators and built-in functions for Python classes. They help us in operator overloading and create features similar to built-in types.

Important Points

  • Magic methods start and end with double underscores (__).
  • Magic methods are used to define custom behavior of operators and built-in functions for Python classes.
  • Magic methods help us in operator overloading and create features similar to built-in types.

Summary

In this tutorial, we learned about Python magic methods and their usage in defining custom behavior for Python classes. Magic methods help us in operator overloading and create features similar to built-in types.

Published on: