Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте What are magic methods? | Magic Methods
In-Depth Python OOP

bookWhat 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:

# What do you use:
len(string)
a + b

# What Python does:
string.__len__()
a.__add__(b)

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.

Note

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:

12345678910111213
class Road: def __init__(self, length): self.length = length def __add__(self, other_road): return Road(self.length + other_road.length) road_1 = Road(20) road_2 = Road(30) road_3 = road_1 + road_2 # road_3 = road_1.__add__(road_2) print(type(road_3)) print(road_3.length)
copy
question mark

What syntax is used for the magic methods?

Select the correct answer

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 5. Розділ 1

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

Awesome!

Completion rate improved to 2.78

bookWhat 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:

# What do you use:
len(string)
a + b

# What Python does:
string.__len__()
a.__add__(b)

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.

Note

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:

12345678910111213
class Road: def __init__(self, length): self.length = length def __add__(self, other_road): return Road(self.length + other_road.length) road_1 = Road(20) road_2 = Road(30) road_3 = road_1 + road_2 # road_3 = road_1.__add__(road_2) print(type(road_3)) print(road_3.length)
copy
question mark

What syntax is used for the magic methods?

Select the correct answer

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 5. Розділ 1
some-alt