Four Two Object Interaction Patterns
Introduction: Four Ways Two Objects Can Interact
Welcome back to Objects Interacting with Other Objects in Python! In the first unit, we watched one warrior act on another: self read its own values and wrote into other. That is one form of interaction, and now, in this second unit, we will expand our toolkit with three more.
Our companion throughout the lesson is a Player class from a small online game, with two players who will compare scores and trade coins.
Setting Up the Players
Let's define the class and the two instances that every later section will reuse. The constructor follows the familiar __init__ pattern.
Two details make this class a good playground for pair interactions:
scoreis a value worth comparing between players, since one number can be higher than the other;coinsis a value worth moving between players, since what one loses, the other can gain.
Comparing Two Instances: Returning a Boolean
Our first new form is the simplest one: a method that asks a question about two objects and answers with True or False. Nothing gets modified here.
The method reads self.score and other.score, compares them, and returns the result. Let's ask whether ada is ahead of lin:
Since ada has 1,200 points and lin has 1,500, the comparison 1200 > 1500 is false:
The comparison is directional, exactly like the direction of an attack in the previous unit: lin.is_ahead_of(ada) would return True, because the call site decides who plays the role of self. Methods that answer yes-or-no questions are conventionally named with an is_, has_, or can_ prefix, which signals to the reader that a boolean is coming back.
Returning One of the Two Objects
A method is not limited to returning numbers, strings, or booleans: it can return an object. Here, we pick whichever player has the higher score and return that player.
The conditional expression reads almost like English: give back self if its score is at least as high as the other's; otherwise, give back other. A few points deserve attention:
>=was chosen deliberately, so a tie resolves in favor ofself; with a plain>, tied players would hand the title toother;selfis an ordinary variable holding a reference, so returning it gives back the very same object the caller already has, not a copy.
This is the same idea as the functions we wrote in an earlier course that looped over a list and returned the "best" object found; the difference is that the choice now happens between just two instances.
