A List of Objects
In the lesson on dictionaries, you kept many pets in a list of dictionaries. A list can hold objects just as well. Each element is one pet, and a for loop goes through them one by one:
class Pet:
def __init__(self, name, species, age):
self.name = name
self.species = species
self.age = age
def describe(self):
return f"{self.name} is a {self.species}."
pets = [
Pet("Rex", "dog", 3),
Pet("Bella", "cat", 5),
Pet("Kiwi", "parrot", 4)
]
for pet in pets:
print(pet.describe())
names = [pet.name for pet in pets]
print(names)Rex is a dog.
Bella is a cat.
Kiwi is a parrot.
['Rex', 'Bella', 'Kiwi']The objects in the list don't need variables of their own: Pet("Bella", "cat", 5) creates a pet right in the list. In each iteration, pet holds one object, so pet.describe() calls the method on each pet in turn, and the list comprehension takes one attribute from each, pet.name.
Printing the whole list doesn't help: print(pets) shows <Pet object at 0x…> for each pet, even in a class with __str__. Print the pets one by one, in a loop.
To find the oldest pet, use max() with a key, as in the lesson on sorting. The key function gets one pet and returns what to compare, its age. Below the program above:
def by_age(pet):
return pet.age
oldest = max(pets, key=by_age)
print(oldest.name)
for pet in sorted(pets, key=by_age):
print(pet.name, pet.age)Bella
Rex 3
Kiwi 4
Bella 5max() returns the whole object, the pet with the largest age, not the age itself, so you can read any of its attributes. sorted() with the same key gives a new list of the pets, youngest first. Without a key, max(pets) ends with TypeError: '>' not supported between instances of 'Pet' and 'Pet': Python doesn't know how to compare two pets. (An instance is another word for an object made from a class.)
Instructions
- 1
A year has gone by. Write a
forloop that callsbirthday()on every pet in the list and then prints the pet. The output should beRex (dog, 4 years),Bella (cat, 6 years)andKiwi (parrot, 5 years), each on its own line. Keep the lines of the list as they are. - 2
Write a key function
by_age(pet)that returns the pet's age. Below the loop, use it withmax()to print the oldest pet:Oldest: Bella (cat, 6 years).