Dunder or Magic Methods in Python: A Comprehensive Guide

Dunder or Magic Methods in Python: A Comprehensive Guide

A Comprehensive Guide to Dunder or Magic Methods in Python: What They Are and How to Use Them

·

4 min read

If you are a Python programmer, you must have come across the term "dunder" or "magic" methods. These methods are special methods in Python that are used for operator overloading, customization of objects, and more. In this article, we will discuss dunder or magic methods, how they work, and how they can be used in your Python code.

What are Dunder or Magic Methods?

Dunder or magic methods are special methods in Python that allow you to customize the behaviour of objects. They are called dunder methods because they have a double underscore (__) before and after their name. These methods are also known as magic methods because they allow you to perform magic by overloading operators such as +, -, *, /, and more.

Python has a lot of built-in dunder methods that are used for different purposes. For example, the __init__ method is used to initialize an object when it is created, the __str__ method is used to represent an object as a string and the __add__ method is used to overload the + operator.

The Syntax of Dunder or Magic Methods

The syntax of dunder or magic methods is very simple. They start and end with a double underscore (__) and have a specific name that describes their purpose. For example, the __init__ method is used to initialize an object, the __str__ method is used to represent an object as a string and the __add__ method is used to overload the + operator.

How to Define Dunder or Magic Methods

To define a dunder or magic method in Python, follow the syntax mentioned above. You need to start and end the method name with a double underscore (__) and provide a specific name that describes the purpose of the method. For example, if you want to overload the + operator, you must define the __add__ method in your class.

Examples of Dunder or Magic Methods

Let's look at some examples of dunder or magic methods in Python.

__init__ Method

The __init__ method is used to initialize an object when it is created. It takes the self parameter, which refers to the instance of the object being created, and any additional parameters you want to pass.

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

person = Person("John", 30)
print(person.name) # Output: John
print(person.age) # Output: 30

__repr__ Method

The __repr__ method is used to represent an object as a string. It is called when you use the repr() function on an object.

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

    def __repr__(self):
        return f"Person(name='{self.name}', age={self.age})"

person = Person("John",30)
print(repr(person)) # Output: Person(name='John', age=30)

__str__ Method

The __str__ method is used to represent an object as a string. It is called when you use the str() function on an object.

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

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

person = Person("John", 30)
print(str(person)) # Output: John is 30 years old.

__add__ Method

The __add__ method is used to overload the + operator. It takes two parameters, the self parameter and another one you want to add.

class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)

v1 = Vector(1, 2)
v2 = Vector(3, 4)
v3 = v1 + v2
print(v3.x, v3.y) # Output: 4 6

__len__ Method

The __len__ method is used to overload the len() function. It takes the self parameter and returns the length of the object.

class MyList:
    def __init__(self, items):
        self.items = items

    def __len__(self):
        return len(self.items)

my_list = MyList([1, 2, 3])
print(len(my_list)) # Output: 3

Conclusion

Dunder or magic methods are powerful tools that allow you to customize the behaviour of objects in Python. They are used for operator overloading, customization of objects, and more. In this article, we discussed what dunder or magic methods are, how they work, and how they can be used in your Python code.

FAQs

  1. What is the difference between __str__ and __repr__ methods in Python?
  • The __str__ method is used to represent an object as a string, while the __repr__ method is used to represent an object in a printable format.
  1. What is the purpose of the __len__ method in Python?
  • The __len__ method is used to overload the len() function in Python.
  1. Can I create my own dunder or magic methods in Python?
  • Yes, you can create your own dunder or magic methods in Python.
  1. What are some common dunder or magic methods used in Python?
  • Some common dunder or magic methods used in Python include __init__, __repr__, __str__, __add__, and __len__.
  1. Why are they called dunder or magic methods?
  • They are called dunder methods because they have a double underscore (__) before and after their name, and they are called magic methods because they allow you to perform magic by overloading operators and customizing object behaviour.
  1. Fluent Python

  2. Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow

  3. Modern Python Cookbook

  4. Advanced Python Programming