Getting Started With Magic Methods
00:00 Before you start working with these magic methods themselves, let’s get an overview of them.
00:06 A magic method in Python is a special function with double underscores that controls how objects behave in certain situations, helping to make custom classes more powerful and flexible.
00:18
To understand what this means, look at this straightforward example. This is a class called Person. You’ve probably come across the __init__ method before.
00:28
It’s used to set up an object’s attributes when you create a new instance of the class. In this example, when you create a Person object, the __init__ method automatically runs allowing you to define the person’s name and age right from the start.
00:43
You’re also creating an instance of your class here, Person( "Alice", 30). This line of code does a few things. First, it calls the __init__ method in the Person class. The "Alice", 30 you see in the parentheses are passed as arguments to the __init__ method where "Alice" is assigned to the .name attribute and 30 to the .age attribute of the new Person object. There you go. You just implemented a magic method.
01:12
You learn more about the __init__ method in the next lesson.
01:17 To understand how Python actually implements these magic methods, let’s take a look at the official Python docs. A magic method is a method that Python calls implicitly or automatically to execute a certain operation on a type such as addition.
01:35 Such methods have names starting and ending with double underscores.
01:40
What does it mean that Python implicitly executes a magic method? It means that when you tell Python to add two and five together, by typing 2 + 5, Python doesn’t just directly add them.
01:52
Instead, behind the scenes, Python calls the __add__ magic method to perform the addition. This method is automatically triggered by the plus operation or the add operation, so you don’t have to call it directly.
02:07 It’s all handled by Python implicitly.
02:11
So far you’ve seen the __init__ magic method in action and learned how Python handles these special methods, but what else is there to know?
Become a Member to join the conversation.
