Methods
A class says not only what every pet has, but also what every pet can do. In the lesson on dictionaries, you wrote a function that describes a pet:
def describe(pet):
return f"{pet['name']} is a {pet['species']}."With a class, such a function goes into the class, indented in its body. A function that belongs to a class is called a method. You've been calling methods for a while, such as names.append("Tom") on a list. Now you'll write your own:
class Pet:
def __init__(self, name, species):
self.name = name
self.species = species
def describe(self):
return f"{self.name} is a {self.species}."
rex = Pet("Rex", "dog")
kiwi = Pet("Kiwi", "parrot")
print(rex.describe())
print(kiwi.describe())Rex is a dog.
Kiwi is a parrot.The first parameter of every method is self: the object the method was called on. In rex.describe(), Python passes rex to self, so self.name is Rex's name. In kiwi.describe(), self is kiwi. One method serves every pet, and each call works with the object before the dot. __init__ is a method too; Python just calls it by itself. A call needs its parentheses: rex.describe without them only names the method and runs nothing.
If you leave self out of the definition, def describe():, Python still passes the object in rex.describe(), but the method has no parameter to take it, and the program ends with a TypeError. You'll fix one in the editor.
Inside a method, you reach the attributes through self. Writing {name} instead of {self.name} in the method above is a typical mistake, and the program ends with:
Traceback (most recent call last):
File "<exec>", line 11, in <module>
File "<exec>", line 7, in describe
NameError: name 'name' is not defined. Did you mean: 'self.name'?Read it from the bottom: the error happened on line 7, in the method describe, which line 11 called. name was a parameter of __init__, a local variable that was gone as soon as __init__ ended. What stays in the object is the attribute, self.name, as the message suggests.
Instructions
- 1
The program ends with a
TypeError. Read its last line, then fix the methoddescribe()so that the program printsRex is a dog.Keep the lines that create Rex and Kiwi as they are. - 2
Add a second method to the class,
age_in_months(self), which returns the pet's age in months: its age times 12. - 3
At the end of the program, print the sentence
Kiwi is 48 months old.Get the number by calling the method on Kiwi:kiwi.age_in_months().