Review the Dog Class
00:00
Let’s start this off by taking a quick walk through the Dog
class just so you remember what is this Dog
class that you’re going to be working with in this review exercise.
00:10
This is the same Dog
class that you built in the Python Basics course that these review exercises are for. That’s the code. I’m going to head over to the IDLE REPL.
00:23
Here we are. I have the code saved, and I will run the code in IDLE using F5. And now I’m over here in the interactive REPL, and I can play around with this Dog
class. Let’s start by creating one instance.
00:39
I’m going to call this one wolf
, and woolf
is the dog with the name "Woolf"
,
00:47
and it’s a puppy, it’s only a year old. So here I’m creating an instance of the Dog
class by passing in a name and an age. This is what’s required according to the .__init__()
method.
01:01
Once I execute that, I have my Dog
object, and I can print()
it to get a nicer representation of what this whole object is about.
01:12
Woolf is 1 years old
, so I get the name and the age of the dog. And then you also have access to a class attribute called .species
, which points to the string, "Canis lupus familiaris"
, which is the scientific name for a dog. And to be precise, it’s actually a subspecies, not a species, because canis lupus is the gray wolf, and all dogs are just subspecies of gray wolf. But this approximation shouldn’t hurt anyone.
01:42
I can also access this class attribute through the instance. I can say woolf.species
,
01:48
and it gives me "Canis lupus familiaris"
. Note that this is a class attribute, so you can also access it through the class. I can say Dog.species
and get the class attribute.
01:59
And that’s generally the better way to access a class attribute because if I would set this woolf.species
to something, I would create a new instance attribute and override the class attribute, basically. But let’s not go into this too much for now.
02:15
We’re just taking a walk through the Dog
class, right? One more thing we can do with woolf
is we can ask woolf
to speak and say—what does woolf
say?—"Woof"
!
02:29
And then we can see that Woolf says Woof
.
02:34
So in this Dog
class, you have one class attribute. You have an .__init__()
method that defines that you need to pass a name and an age when you instantiate the Dog
.
02:47
And these two get assigned to the instance. Then you also have a .__str__()
method defined, which gives you a readable representation when you print()
a Dog
object.
02:59
And then you have one more instance method that is called .speak()
, and this one takes as an attribute a sound and then returns a string that really just says the name of the dog and what sound they make.
03:12
This is the parent Dog
class that you’re going to be working with in the next review exercise. I hope you enjoyed that walk through the dog park, and see you over in the next lesson, where I get started with the exercises.
Become a Member to join the conversation.