Subclass

Flash and JavaScript are required for this feature.

Download the video from iTunes U or the Internet Archive.

Description: This in-class question demonstrates how subclasses are constructed in Python.

Instructor: Dr. Ana Bell

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 I have here-- first part is just the top part, so I have some blank line and then I'm defining a method name speak. So write a line to replace blank that creates a class for a Dog that inherits from Animal. So the first thing I notice is that I need to write a definition for a class whose name is Dog.

So my choices are these. So I can tell it's either the first or the third one. And then I want to inherit from Animal, so I don't want to inherit from object but I want to inherit from Animal, right? So that's perfect.

Next question says, with this definition of Dog, you run a program with those three lines. What happens? So this is my definition and I have these three lines. Let's go down here. Nice. OK.

So with these three lines, this first line says, d is equal to Dog 7. So I'm creating a Dog object with age 7. Is this line going to throw an error? Well, this line actually looks for an init method.

This particular class definition doesn't have a init method, but hey, I'm inheriting from someone. I'm inheriting from Animal. Does Animal have an init method? And it does, as we saw in the slides. OK, so we're creating a new Dog with age 7 and name none. So that line doesn't throw an error.

The next line sets the name to Ruffles. And again, I don't have a set name method inside this particular class, but does my Animal class-- my parent class-- have a set name method? And yes it does-- right here. So I call that one. So that line does not throw an error.

And the third line says d.speak, which is going to cause Python to look in this current class definition. And it says, hey, I have a method here named speak, so I'm going to use this one. And it's going to print ruff ruff, because it's a method, so you can just-- it's like a function. You can just print things. You don't need to return anything. So, perfect, most of you are getting that right.

Free Downloads

Video


Caption

  • English-US (SRT)