Attributes
Attributes work like variables that belong to an object. You read them after a dot, and you change them with =, += or -=, as you change variables. In this exercise, Pet has a third parameter, age, as the pet dictionary had a third key:
class Pet:
def __init__(self, name, species, age):
self.name = name
self.species = species
self.age = age
rex = Pet("Rex", "dog", 3)
kiwi = Pet("Kiwi", "parrot", 4)
rex.age += 1
print(rex.age)
print(kiwi.age)4
4Rex is a year older, and Kiwi's age hasn't changed: each object has its own attributes. rex.age and kiwi.age have the same name, but they are two different values, just as two dictionaries can each have their own "age".
An attribute doesn't have to come from a parameter. __init__ can also give it a starting value that every new object gets. In the dictionary, Rex had "vaccinated": True; with a class, every new pet can start out unvaccinated:
class Pet:
def __init__(self, name, species, age):
self.name = name
self.species = species
self.age = age
self.vaccinated = False
rex = Pet("Rex", "dog", 3)
print(rex.vaccinated)
rex.vaccinated = True
print(rex.vaccinated)False
TruePet("Rex", "dog", 3) still takes three arguments, because vaccinated isn't a parameter. You change it later, once the pet has been to the vet.
Reading an attribute that the object doesn't have ends with an error: print(rex.color) ends with AttributeError: 'Pet' object has no attribute 'color'. The message names the kind of object, 'Pet', and the attribute that Python didn't find. Most often it's a typo, such as rex.nmae, or rex.Name with a capital letter. You've met this error before, for a method that a value doesn't have, such as join() on a list: to Python, a value's methods are its attributes too.
When you assign, though, a typo doesn't end with an error. rex.agee = 4 works like a new key in a dictionary: it creates a new attribute, agee, and rex.age stays as it was.
Instructions
- 1
The program ends with an
AttributeError. Read the last line of the message, then fix theprint()so that it printsRex is 3. Keep the lines that create Rex and Kiwi as they are. - 2
Rex has had his birthday. At the end of the program, increase his age by 1, then print the ages of both pets, each with its name:
Rex: 4andKiwi: 4. - 3
Every pet should also know how hungry it is. In
__init__, add an attributehungerthat every new pet starts with at5, without a new parameter. At the end, print Kiwi's hunger:Hunger: 5.