Introducing Instance Methods
00:01 Instance methods. Now you’re getting to things that really make objects come alive, where you can really customize their behavior.
00:08 Instance methods are attached to instances by the name, so when you instantiate an object, you have access to these methods, which are like functions, but they are attached to the instances.
Looking at the
Doggo class from before, you’ve got your constructor method, and the way you add more methods is to use the same syntax as defining a function.
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.
01:36 So it’ll return a string that uses an instance attribute to get the name, and then uses the sound that you passed in as an argument.
What does that look like when you use it? Well, say you instantiate your dog
miles. His name is
"Miles", and he’s
4 years old.
And then you call the
.description() method. You call this in the same way that you would an attribute with the dot notation (
.), except since it’s a method, you have to call it.
You don’t have to pass in the
self. Remember, the
self is automatically passed in. So if this method doesn’t have any parameters other than
self, then you’re good to go.
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.
02:45 It’s just like a function that lives in a class, which are available on the instantiated objects from that class.
Become a Member to join the conversation.