Collaborators Without Casts
Lesson 38 of 48 in Coddy's Python for Java Developers course.
Let an object delegate work to a collaborator it stores. Java commonly declares a field with an interface type and accepts an implementation in its constructor. Python can call the collaborator's method without declaring a common base class. The required behavior still matters: cost must accept units and return the promised result. Looking up self.rate during each total call allows the collaborator to be replaced later. This is composition, a has-a relationship, not inheritance.
Java excerpt: class member declarations
// Class members
interface Rate { int cost(int units); }
static class Bill {
Rate rate;
Bill(Rate rate) { this.rate = rate; }
int total(int units) { return rate.cost(units); }
}Python
class Bill:
def __init__(self, rate):
self.rate = rate
def total(self, units):
return self.rate.cost(units)Watch the difference
Do not copy a collaborator's formula into its client or cache one computed total. Either choice bypasses future behavior changes. A missing cost method fails at runtime unless separate tooling catches the mismatch; duck typing is not automatic validation.
Practice
Apply this comparison in the task below. Editable files: rate.py, usage_bill.py. Keep the provided imports and the required API names. The locked driver.py supplies execution and checks; do not edit it.
Challenge
BeginnerImplement Rate(cents).cost(units) as multiplication, and UsageBill(rate).total(units) by delegating to its stored current rate.cost(units). The driver reads rate, units, replacement rate, and bonus (nonnegative integers), prints the first total, replaces the collaborator with an object computing replacement_rate * units + bonus, and prints again. As with dependency injection through a Java interface, the bill must use the supplied behavior rather than duplicate its formula.
Editable files: rate.py, usage_bill.py. Keep the provided imports and the required API names. The locked driver.py supplies execution and checks; do not edit it.
Implement the named definitions in the editable modules without input or printing. The driver owns input/output and may call the APIs again on fresh data without producing extra output.
Try it yourself
from rate import Rate
from usage_bill import UsageBill
class BonusRate:
def __init__(self, cents, bonus):
self.cents = cents
self.bonus = bonus
def cost(self, units):
return self.cents * units + self.bonus
cents, units, replacement, bonus = [int(input()) for _ in range(4)]
bill = UsageBill(Rate(cents))
print(bill.total(units))
bill.rate = BonusRate(replacement, bonus)
print(bill.total(units))
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for Java Developers
1From Java Classes to Python
Run Python Without a ClassPrinting Text and CommentsBindings, Types, and finalDivision and Numeric TypesIndentation Defines BlocksRecap: A Python Receipt4Iteration and Transformations
Enhanced Loops and rangeIndexes and Map EntriesSentinels and Loop ControlFrom Streams to ComprehensionsRecap: Stable Ranking2Values Beyond Java Primitives
None and Boolean ValuesValue Equality and IdentityTruth Tests Beyond booleanBranches and Value SelectionRecap: Missing or Eligible5Functions Beyond Methods
Functions Outside ClassesDefaults Instead of OverloadsVarargs and Keyword OptionsScope and Callable ObjectsRecap: Pricing Functions8Behavior Beyond Interfaces
Collaborators Without CastsInheritance and InitializationInterfaces and Duck TypingRecords and Data ClassesRecap: Pluggable Channels3Collections and Object Sharing
Lists and ArrayList HabitsTuples Without Record ClassesDictionaries and Java MapsShared References and CopiesRecap: Inventory Collections6Contracts, Errors, and Modules
Text Input and Exact OutputValueError and TypeErrorModules Versus Utility ClassesAnnotations Are Not Java TypesRecap: Validate a Batch9Project: An Order Processor
Project: Model an OrderProject: Pricing PoliciesPractice on your own: Online Python compiler