Driving Object Interactions
Introduction: Who Gives the Orders?
Welcome back to Objects Interacting with Other Objects in Python! We are now in the third unit, and so far, every interaction has been triggered the same way: We typed warrior.attack(target) or ada.trade(lin, 15) directly at the top level of our program. The objects knew what to do, and we decided, by hand, when they did it.
In this unit, that decision moves into a plain function. The function receives one or two objects as parameters and calls their methods in a chosen order. You may recall functions receiving objects from the very first course; back then, they read and wrote attributes directly. Now, they will call methods instead, which is cleaner and safer.
Our theme is a small space battle built around a Spaceship class, and we will climb four levels: driving one object, driving one object to act on another, making both act in one call, and finally looping until only one ship is left.
The Spaceship Class: Our Building Block
Before writing any driver function, we need something to drive. Here is the complete class, with a familiar __init__ and three short methods.
Each method plays a distinct role in the lesson:
fire_at(other)is the two-object method from Unit 1: It readsself.firepowerand writes intoother.shields.recharge()touches onlyself, raising its own shields by 10.is_flying()changes nothing; it simply reports whether the ship is still in the fight, and later, it will serve as the stopping condition of our loop.
Two ships will accompany us through every remaining section:
The cruiser is tougher, with 120 shields, while the raider hits harder, with 30 firepower.
A Function That Drives One Object
Our first driver is as small as a function can be: It takes one ship and calls one method on it.
The parameter ship is not a copy: It is a second name pointing to the exact same object as cruiser. So, when recharge() adds 10 to self.shields, that change is written into the one and only cruiser and remains visible after boost returns.
Shields climb from 120 to 130. Note that boost(cruiser) and cruiser.recharge() do exactly the same thing here. A wrapper like this earns its keep once it grows — when it needs to log the action, check a condition first, or call several methods in a row.
