Extend a Method (Solution)

00:00 The task was to provide a default value of "Bark" for the Dog.speak() method.

00:14 What you’re going to need to do here is to define a .speak() method in the GoldenRetriever class. This is going to override the .speak() method from the parent class.

00:20 So if I say def speak(self, sound), here, then this is going to override the method that is defined in the Dog class because it has the same name. You don’t really want to override it.

00:30 You just want to augment it. You want to extend it with this default argument. First of all, let’s see how we can create a default argument in Python. That is by using an equal sign here and then passing the default value to the argument, I’m going to say this is "Bark".

00:49 And now I don’t want to define this return string another time. I want to keep using the one from the parent method. And in order to do that,

00:56 I need to actually reference the method on the parent class inside of my .speak() method in the child class. And I can do that by saying super().

01:06 That gives me access to the parent class. And then I’m going to call the .speak() method from the parent class, and I will pass it the sound. And this, again, is going to be whatever sound you pass in when calling .speak() on a GoldenRetriever object. But if you don’t pass in any sound, then it’ll use the default value of "Bark" that you defined here.

01:33 Just calling it like that is not enough. You would also need to return this. So I’m going to add a return statement here, and with that,

01:42 that should be it. I think we’re done. Let’s test it out. I’m going to run the script and go into the interactive mode in the REPL. And now let’s create another GoldenRetriever.

01:54 I’m just going to copy the code I used before, and we’ll work with buddy again. And now I should still be able to say buddy.speak() and pass it a string.

02:04 So for example, I’m going to say buddy.speak() and then pass it "Howl" and Buddy says Howl. But now if I am going to call .speak() on buddy without passing an argument, then it should default to "Bark" like I defined in the .speak() method on the GoldenRetriever class and it’s working: Buddy says Bark.

02:25 So what I did here is I extended the .speak() method of the parent class by providing a default argument to sound,

02:38 and it’s an extension of the parent class method because you’re calling the method in the body of your .speak() method in the child class. If you wouldn’t call it, then you would effectively override the method from the parent class with a

02:58 new method. All right, task done. Let’s do a quick recap on these review exercises and then head off to our challenge.

Become a Member to join the conversation.