Python Magic Methods

What are Magic Methods in Python?

Magic methods are used to define how objects of a class behave in various situations, such as arithmetic operations, comparisons, and string representations.

Magic methods are special methods in Python that have double underscores at the beginning and end of their names. Magic methods also known as dunder methods (short for “double underscore”).

Magic methods provide a way to customize the behavior of built-in Python operations and make user-defined classes more intuitive and powerful.

How to define Magic Methods in Python

Defining magic methods is straightforward. They are already predefined in Python classes with certain default behaviors, but you can override them to customize the behavior for your own classes.

For example

  • to define a custom behavior for addition, you can override the __add__() magic method.
  • to define a custom string representation for a class instance, you can override the __str__() magic method.

Examples

Let’s explore examples of using magic methods to customize the behavior of Python classes.

1. Custom String Representation using Magic Method __str__()

In the following program, we have defined a class Person. When you print an instance of this Person class, its string representation is printed out, as shown in the following program.

Python Program

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

person = Person("Ram", 25)
print(person)
Run Code Copy

Output

<__main__.Person object at 0x100f11450>

Now, let us override how this string representation is done. Define a custom string representation using the __str__() magic method:

Python Program

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return f"{self.name}, {self.age} years old"

person = Person("Ram", 25)
print(person)
Run Code Copy

Output

Ram, 25 years old

We have overwritten the default string representation behavior of a class with required string representation by overriding the magic method __str__().

2. Custom Addition Operation using Magic Method __add__()

In this example, we defined a class ComplexNumber to define a complex number, that has real and imaginary parts. When two instances of this object are added, we would get TypeError, as shown in the following program.

Python Program

class ComplexNumber:
    def __init__(self, real, imag):
        self.real = real
        self.imag = imag

c1 = ComplexNumber(2, 3)
c2 = ComplexNumber(4, 5)
result = c1 + c2
print(f"Result: {result.real} + {result.imag}i")
Run Code Copy

Output

TypeError: unsupported operand type(s) for +: 'ComplexNumber' and 'ComplexNumber

We can change this behavior by overriding __add__() magic method for ComplexNumber, as shown in the following program.

Python Program

class ComplexNumber:
    def __init__(self, real, imag):
        self.real = real
        self.imag = imag

    def __add__(self, other):
        real_sum = self.real + other.real
        imag_sum = self.imag + other.imag
        return ComplexNumber(real_sum, imag_sum)

c1 = ComplexNumber(2, 3)
c2 = ComplexNumber(4, 5)
result = c1 + c2
print(f"Result: {result.real} + {result.imag}i")
Run Code Copy

Output

Result: 6 + 8i

In this example, the __add__() magic method is defined to customize the addition operation for the ComplexNumber class.

Summary

In this tutorial of Python Classes and Objects, we have learnt about Magic methods in Python, and how to customize the behavior of classes, with examples.

Related Tutorials

Code copied to clipboard successfully 👍