Class Instance

Flash and JavaScript are required for this feature.

Download the video from iTunes U or the Internet Archive.

Description: This in-class question explains the how a class instance is initialized in Python.

Instructor: Dr. Ana Bell

The following content is provided under a Creative Commons license. Your support will help MIT OpenCourseWare continue to offer high quality educational resources for free. To make a donation or view additional materials from hundreds of MIT courses, visit MIT OpenCourseWare at ocw.mit.edu.

PROFESSOR: We have this definition for the class object. I've created the init for you. And here I'm giving it "self," which is the first thing that you have to give it, and then two parameters-- w and d. And for an instance of a car, I'm going to assign the data attribute named wheels to whatever is passed in for w. So notice that they're not the same name.

And the data attribute for "doors" is going to be the value that's passed in for d OK? And also notice that inside init, I can do any other sort of initializations that I'd like. So it's not just assigning variables from the parameters to variables for my objects. So in this case I'm creating a new data attribute named "color," and I'm going to just create it to be an empty string OK, even though I didn't pass in any color to my object.

So the question says, "Using the class definition above, which line creates a new Car object with 4 wheels and 2 doors?" OK? So this first one is not right, because it's trying to call the class with a variable mycar for self, which isn't quite right. So when you're creating your object, you have to give it one less parameter than what you have. So here we're just going to have to create it with the w and the d.

So we're going to create this variable mycar and we're going to assign it 4 for the number of wheels and 2 for the number of doors. And the number of wheels is the first parameter, and the number of doors is the second one, so it should be this one here-- Car 4 comma 2. So that's this one. Perfect.

Free Downloads

Video


Caption

  • English-US (SRT)