Create a Child Class (Solution)

00:00 To create a child class from a class, what you need to do is, again, use the class keyword, then type in the name of your class, so GoldenRetriever, and then you can open up parentheses here and then put in the parent class and then close the parentheses and finish it off with a colon as usual. In the next line, I’m going to for now put a pass keyword just to satisfy Python’s need for some indented code after a colon, but I’m not going to implement any functionality in the child class so far.

00:37 That’s really all you need to do to create a child class. After the name of the child class, you have to put the name of the parent class in parentheses. That’s it.

00:47 And now GoldenRetriever has all the functionality that the Dog class has as well as all the attributes. So we can try that out. I’m going to run the code

00:58 and jump over in the interactive shell. And now I’m going to make a GoldenRetriever. We call him, buddy. GoldenRetriever() and again, it needs a name and an age. We called him buddy, so let’s stick with that. It’s an old dog, 12 years old. No complaints.

01:26 So now I have an instance of GoldenRetriever. Here you can also see that if I print() the representation of Buddy, then it says in the main namespace, I have a GoldenRetriever object at a certain memory location.

01:40 Great, and what can buddy do? buddy can speak().

01:49 I can print(buddy). So the .__str__() also gets taken over from the parent class, So the same format. you can also access the class attribute through the instance—what’s it called?—.species.

02:07 And you can see that it’s still a Dog. All right, so with this short two lines of code, you created a child class that inherits from the Dog parent class.

02:19 Let’s see what else we can do to review everything that you’ve learned in the associated course.

Become a Member to join the conversation.