Initializing Objects With __init__()
00:00
You quickly looked at the __init__
magic method in one of the previous lessons. Now, let’s dive deeper and really understand how it works. First, let’s refresh your memory. Instance attributes are properties or characteristics that are specific to each object of a class.
00:19
Now let’s see how __init__
comes into play here. Check out this Dog
class. In this example, you’ve got a Dog
class with an __init__
method. As you learned before, the __init__
method is a special method that Python automatically calls when you create a new instance of the class.
00:37 Its main job is to set up the instance’s attributes.
00:41
Now, meet Buddy and Lucy. Each has a unique name and age, so name
and age
are instance attributes of the class Dog
.
00:51
Each Dog
object can have its own name and age.
00:56
How does __init__
do this? When you create a new Dog
instance, __init__
initializes the newly-created object by setting up its initial state.
01:06
Then it assigns values to its instance attributes. For example, for Buddy, it passes “Buddy” as the name, and 5
as the age. Inside __init__
, .self
.name
is set to “Buddy” and .self
.age
is set to 5
.
01:22
Now the Buddy object has these attributes. The same thing happens for Lucy. As you might have noticed, you don’t have to call __init__
by yourself.
01:33 You just rely on Python’s implicit behavior.
01:37
So far, you’ve created two new instances of the Dog
class, but how does Python actually create a new instance behind the scenes? To find out, keep watching.
Become a Member to join the conversation.