Managing Object Collections
Introduction: From Two Objects to Many
Welcome back to Objects Interacting with Other Objects in Python! We have reached the fourth and final unit of the course. So far, every interaction has involved one or two named objects: a warrior and a target, two players trading points, or a cruiser and a raider locked in a dogfight. That was enough to explore how objects reach into each other.
Real programs, though, rarely stop at two. They manage a crowd: a party of heroes, a fleet of ships, or a roster of players. This raises a practical question we have not faced yet: once we have many objects, how do we work with all of them without writing the same code over and over? This unit answers that question, using a small adventuring party built from a Hero class as our running example.
To keep the spotlight on the collection itself, we also step back from the driver functions of earlier units and return to plain method calls.
The Hero Class: One Reader, One Changer
Everything in this unit rests on a class with just two methods, deliberately chosen to sit on opposite sides of the read/write line.
Here is how the pieces divide the work:
__init__stores two attributes per hero, so every instance carries its ownnameandlevel.describe()only reads state and returns a string; it changes nothing.level_up()only changes state and returns nothing; it adds1toself.level.
Notice that every Hero, whatever its name or level, exposes these same two methods. That shared interface will matter shortly, once we start processing heroes together.
Building the List of Objects
With the blueprint ready, we can create three heroes. A natural place to keep many objects together is a single list, written here as one literal.
Each Hero(...) call runs __init__ and produces a separate object, so party holds three references to three independent heroes, not three copies of one. The list itself behaves like any other list we have used: len(party) returns 3, and party[0].name reads "Aria" by combining indexing with dot notation.
The relationship between the list and the three independent objects can be pictured like this:
Notice that no hero is stored in its own named variable. The list is the only handle we need, and we could just as easily have started from party = [] and added heroes with append().
