Let the Animals Talk
00:00
I’m going to start with .talk()
and implement the method for each animal to say something. And I’ll just return a string here, an f-string
00:12
where the name of the animal, self.name
, inside of the curly braces says the .sound
in the curly braces. And I don’t want this to fail if you don’t pass an argument to .sound
, so I’ll give it a default argument of, well, what does every animal do? I guess they all sleep.
00:34
So I’ll put in there. That’s my default argument. So this is really just a protection for me that if someone implements the .talk()
method in one of the child classes but doesn’t pass in a default sound and then someone calls it without a default sound, I don’t want this to break. So that’s why we have a default in here.
00:55
But I’m going to go ahead and override that right away in all of the classes that I have so far. So let’s do a bit of extending a method. I have .talk()
in the child class Dog
, and it’ll take self
and sound
.
01:10
And here my default argument is going to be "Bark"
.
01:17
And otherwise I don’t need to write that string again so that I can change it in the parent class, and it’ll trickle down to all of the child classes. I’m going to call super()
and then the .talk()
method of super()
and pass it the sound
.
01:35
And of course, I will have to return this. All right, so this is an extension of the parent class’s .talk()
method. We’re essentially overriding the default sound that a dog makes.
01:49
And I’m going to say that this is "Bark"
, and I’ll do the same for the Pig
, which says "Oink"
, and also the Sheep
, which says "Baaa"
, three a’s.
02:08 Okay, so this should give me the possibility to have each instance of each of those three child classes talk and give a different default sound. But also I can still pass in a sound and then make them say whatever they want.
02:28
Okay, here we are. Let’s make a new Dog
, called "Puppy"
. "brown"
Puppy, and this one is "happy"
.
02:42
And then I can use the .talk()
method and call it without an attribute, and Puppy says Bark
, and I can still make it say "Hello"
, for example. It’s a very educated puppy.
02:58
Puppy says Hello
. Great. And that same thing should also work for Pig
and Sheep
.
03:13
Smart pig. And then I can say pig.talk()
, and Lizzy says Oink
. And I can also make Lizzy
say "Pigs are smart"
. All right, great.
03:28
So this works. I can call the .talk()
method on Dog
and Pig
instances, and also Sheep
instances. Haven’t tried that out now, but same code.
03:38 So it should work as well. And it gives me the default sound of that animal when I call it without arguments, and I can still pass in an argument, and then it prints that out instead.
03:50
So with .talk()
done, let’s move on to the next method.
Become a Member to join the conversation.