Introducing Instance Methods
You have the
def keyword, then you have the name of the function, and then you have the parameters that you pass to that function. Note here that all methods have the
self keyword as the first parameter.
This is very important to remember because this is always passed to the function as the first argument by default. This is what gives you access to the instance attributes, such as
Here you can see in the
.description() method that it just returns a string, but it uses the attributes to build that string. So if you call
.description(), you’ll get a string that will give you the name and the age of the dog and will say it’s a good doggo. You have another instance method with the
self keyword, but in this one, in the
.speak() instance method, you pass in an argument,
sound, and so when you call this, it will return a string that will use the instance attribute of
.name, and it will say the sound that you pass in as an argument.
You just have to call it without any arguments, and you’ll get the string. It grabs the name, it grabs the age, and it creates the rest of the message for you. With the
.speak() method, again, you’re calling it with a
. operator, and since this one does take an argument, the sound that you want Miles to say, you have to pass in that as a string.
'Miles says Woof
'Miles says Bow Wow'. That’s how instance methods work.
Become a Member to join the conversation.