In Python, classes provide a clean means to bundle data and functionality together into reusable elements. Creating custom classes allows you to model real-world entities like users, products, and employees.

Python classes define magic methods that you can customize to allow you to shape the behavior of your classes for unique situations.

woman blowing sprinkle in her hand

Understanding Magic Methods

Imagine magic methods, also called dunder methods, as secret spells or hidden chants that Python automatically calls when you perform certain actions on an object.

Python provides a lot of built-in behavior for classes throughinstance, static, and class methods. You cancreate Python classes, and customize them even further using magic methods.

default string representation of object

Magic methods are instance methods in Python that have two underscores (method) before and after the method name.

These special methods give instructions to Python on how to handle objects of a class. Here are some commonly used magic methods in Python classes:

customized string representationof an object

Implementing Magic Methods

The best way to understand magic methods is by using them.

String Representation of an Object

You can customize the string representation of an object for readability or further processing.

Here you have a simplePersonclass with an__init__magic method to initialize it. When you print thep1object, it uses the default string representation provided by Python.

modified len property

To customize the string representation, define the__str__and__repr__magic methods:

Now you have a more readable and comprehensive string representation of thep1object:

Length Property of an Object

Imagine that, when you call thelen()method of a Person object, you want their height. Implement the__len__magic method for thePersonclass:

The__len__magic method returns the height attribute of aPersoninstance. When you calllen(p2), it will call the__len__magic method automatically which returns the height of thep2object.

comapring two objects of the same class

Handling Comparison Between Objects

If you need to compare objects of a class based on certain properties of the class. you may define__eq__magic method and implement your comparison logic.

The__eq__method compares thenameandageattributes of the twoPerson’sobjects to determine equality.

The double equal to (==) operator uses this method to check for equality rather than comparing identities. So twoPersoninstances are equal if they have matching name and age attributes. This allows you to override the default equality-checking behavior for your custom class.

By implementing these magic methods, you can define custom behavior that will be consistent with Python’s built-ins.

Advanced Magic Methods

Here are some advanced examples of using magic methods to customize classes.

Making Classes Act Like Containers

Using magic methods you can define classes that behave like containers. You can usecontainers, like tuples, to store collections of data elements. They provide various methods to manipulate, access, and iterate through the contained elements.

Now a Person object can behave like a container:

Customizing Attribute Access

Using the__getattr__magic method you’re able to customize the way attributes of thePersonclass are being accessed based on certain conditions.

The__getattr__method will run when you try to access an attribute that doesn’t exist directly in the object. In this case, it checks if the attribute name isageand returns 40.

For any other attribute name, it raises anAttributeErrorwith a corresponding message.

Making Classes Behave Like Callable

The__call__method allows you to treat an instance of the class as a callable object (i.e., a function).

When you create an instance ofAdderand then call it with arguments, the __call__method runs and performs the addition before returning the result.

Operator Overloading

Using magic methods you may perform operator overloading. Operator overloading allows you to define custom behaviors for built-in operators when used with instances of your own classes. Here’s a common example that explains operator overloading.

The result is a new vector:

TheVectorclass defines the__add__method, which runs when you use the+operator between two instances of the class. The method adds the corresponding components of the two vectors and returns a newVectorinstance with the result.

Here you’ve seen fundamental magic methods which you can implement to customize your class behavior. Python has many more magic methods which offer more flexibility when creating classes. Refer to theofficial documentationfor a complete list.

Object-Oriented Programming in Python

Magic methods in Python provide powerful ways to customize and enhance the behavior of classes. Magic methods go along with the concept of object-oriented programming (OOP) in Python. So it is important to understand the concept of OOP when trying to use magic methods.