Create Parent and Child Classes
00:00
I’ll start with building this class by just taking a quick note. Again, I want an Animal
class with three subclasses representing animals.
00:13
First, it’s going to be the Animal
class, so I’ll say class Animal
00:19
pass
, and then I need three subclasses. I want a Dog
that inherits from Animal
.
00:29
I’m going to have the same structure, so just going to copy that three times. Second one was a Pig
and then a Sheep
. Of course, you can model other animals.
00:39
The point is that they all inherit from Animal
, which you do with this syntax of parentheses, and then the name of the parent class. It’s also good practice to have two spaces between classes just to make it a little easier to read. We have a parent class Animal
, and three child classes, and then let’s make it a little less boring and define an initializer def __init__()
, and this takes self
. What else?
01:10
I’m going to stay with name
and color
and assign them to instance attributes. self.name
equals name
and self.color
equals color
. With this code, we have a parent class with two attributes so far, and then three child classes that inherit from it. That’s a good start, but how can we distinguish what is a Dog
and what is an Animal
?
01:38 It could be nice to have an attribute for that. Well, let’s do that in the next lesson.
Become a Member to join the conversation.