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.
00:21
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.
00:33
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.
00:46
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 .name or .age.
01:01
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.
01:44
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.
01:54
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.
02:04
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.
02:14
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 Woof' or '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.
Get a Python Cheat Sheet (PDF) and learn the basics of Python, like working with data types, dictionaries, lists, and Python functions:

