course content

Course Content

In-Depth Python OOP

What are magic methods?What are magic methods?

Python is a very flexible programming language, and the magic methods provide this flexibility.

Magic Methods are methods with specific syntax that provide functionality for different operations in Python.

For example:

The a + b operator invokes the __add__() magic method of the first object (a.__add__(b)). In Python, operators like + call the corresponding magic methods of the objects involved. The __init__ magic method is called when an instance of a class is created.


Magic methods have a specific syntax where the method name is enclosed in double underscores (__) at start and end of method name.

Let's take a look at an example implementation of the __add__ magic method:

Code Description
In this code, a class called Road is defined. The Road class has an __init__ method that takes a parameter length and initializes the length attribute of the instance with the provided value.

The Road class also defines the __add__ method, which enables the class instances to support the addition operation (+). This method takes two parameters: self (representing the instance on the left side of the + operator) and other_road (representing the instance on the right side of the + operator). Inside the __add__ method, a new Road instance is created, with its length attribute set to the sum of the length attributes of the two instances being added. This allows two Road instances to be added together, resulting in a new Road instance with a combined length.

In the subsequent lines of code, three instances of the Road class are created: road_1 with a length of 20, road_2 with a length of 30, and road_3, which is obtained by adding road_1 and road_2 using the + operator.

The print(type(road_3)) statement prints the type of road_3, which should output , indicating that road_3 is an instance of the Road class.

The print(road_3.length) statement prints the length attribute of road_3, which should output 50, representing the combined length of road_1 and road_2.

Overall, this code demonstrates the use of the __add__ special method to define custom addition behavior for instances of the Road class. It allows two Road instances to be added together, resulting in a new Road instance with a combined length.


What syntax is used for the magic methods?

Select the correct answer

Everything was clear?

Section 5. Chapter 1