Understanding the Constructor and Attributes
In this lesson, you’re going to cover the constructor and attributes. That means you’re going to be covering the
.__init__() constructor. That’s quite a mouthful, so in Python, the
__ is often shortened to dunder—d for double, under for underscore, d under, dunder.
So you can say the dunder init constructor. The
.__init__() method is also sometimes referred to as just the constructor method or simply the constructor. Now, you may have noticed I called it the method.
00:39 You’ll note in a second that the constructor looks a lot like a function, and in many ways, it is a lot like a function. But in Python, functions that are part of classes are called methods, making this not the constructor function, but the constructor method. You’ll be getting into more on methods later in the course. You’ll be covering attributes, which is basically where the information lives in classes.
self, you can think of it as a normal function that accepts parameters. In this case, since you’re defining a point, you want the
y coordinates, and so those are the parameters for your function. As usual, you have your colon, and you start with the indented block to define the function body.
Here’s another example. In this case of
Doggo, you have the
self keyword as before, but in this case, instead of passing in the
y, you’re passing in a name and an age, because those are the only bits of information that you’re interested in right now. And it follows much the same pattern. You take
self, which represents the instance.
but you’ll get an error if you have parameters to your constructor. Using the brackets after the
Point will automatically call the constructor, so you can think of this as a call to this function.
As you can see, you’re getting some suggestions here, so let’s say
10, and now that will instantiate properly. You’re going to be covering instantiation with attributes in a later lesson, but that’s basically what it looks like in practice.
It’s a convention to call it
self. It’s just the first thing that’s passed to the constructor methods. You can call it
I or anything else you like, but don’t call it something else because everyone in the Python world calls it
self, and you’ll see that in examples everywhere. So just don’t think about it.
So when you instantiate a class, what happens is that you’re calling the constructor if there is one. You define the
self parameter of the function, and then you can assign the attribute values to the
But usually what you want to do is instantiate the object, pass in a bunch of values, and you want those values to end up on the instance of the class, and the way you assign them is with the
self. whatever the attribute is you want and you assign it the value. Any instance setup that you want to do, any building of lists or dictionaries or more attributes or calculated values, you can stick all of that in the constructor.
Become a Member to join the conversation.