Description: This in-class question explains how and why class attribute getters and setters are important 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.
ANA BELL: So we have a class Car here, object as usual. The init method here takes in self as usual, a w, and a d. So Car gets initialized with two parameters. And we assign the wheels data attribute to the first one and the doors data attribute to the second one. And then we're going to also assign the color data attribute to be the empty string.
So I'm giving you four choices here. And the question says, which of the above is a getter method for the number of wheels? So getter method is something that's going to get a data attribute. A method is really just a function.
So of course, we're going to have def. get_wheels is a good name for it. Since it's a method for this class, we have to have self in the parameters. So we know it's going to be between C and D.
And so then what are we going to return? The first one's going to return wheels, which, in this particular case, is just going to be a variable that we haven't defined, but it's a variable. A getter returns a data attribute of a particular instance.
So we actually have to say self dot if we want to return a data attribute of an instance, as opposed to just a regular variable. So the correct answer is D. Great job.