Collaborator Objects
Lesson 38 of 48 in Coddy's Python for Dart Developers course.
Dart composition stores a collaborator in a typed field; Python can store the same relationship in an ordinary attribute. A bill delegates cost calculation to a rate object. Python does not require a declared interface for that call, but the method must exist and accept the expected arguments at runtime. Sharing the collaborator shares its mutable state, so decide whether two bills should observe the same rate changes. Keep classes in separate modules when that makes responsibilities clear. Composition lets callers change a collaborator without inheriting its entire implementation, in either language.
Dart
class Rate {
final int cents;
Rate(this.cents);
int cost(int units) => cents * units;
}
class Bill {
final Rate rate;
Bill(this.rate);
int total(int units) => rate.cost(units);
}
void main() { print(Bill(Rate(7)).total(2)); }Python
class Rate:
def __init__(self, cents):
self.cents = cents
def cost(self, units):
return self.cents * units
class Bill:
def __init__(self, rate):
self.rate = rate
def total(self, units):
return self.rate.cost(units)
print(Bill(Rate(7)).total(2))Porting trap
Do not discard the collaborator after computing one sample result if later calls must delegate with different inputs.
Challenge
BeginnerImplement Rate(cents) with cost(units) returning cents times units, and UsageBill(rate) that stores its collaborator as rate. Its total(units) must delegate to the collaborator's cost(units). Input is four nonnegative integers on separate lines: rate, units, replacement rate, and bonus. The locked driver prints the first total, replaces the collaborator with a ready-made object whose cost is replacement_rate * units + bonus, and prints the new total. A bill must use its current collaborator, not cache a formula or initial result.
The locked driver handles input and output. Submit only the required class and function definitions with the exact API names. Do not read input or print from your classes.
Your code goes in the editable files rate.py and usage_bill.py. driver.py holds the supplied input/output code and API checks and cannot be edited. Keep the supplied imports; do not read input or print from the editable modules.
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 Dart Developers
1From Dart to Python
Run Your First Python ProgramInterpolation and printvar, final, and Python NamesFloor Versus TruncationBraces and Block ScopeRecap: Rewrite a Receipt4Iteration and Transformations
for-in and rangeentries and enumerateLoop Updates and continuewhere, map, and List BuildingRecap: Build a Ranking2Values and Decisions
Null Safety and NoneList Equality ChangesConditions and Null DefaultsTernaries and elifRecap: Eligibility Rules5Functions and Closures
Arrows and Explicit ReturnsNamed Calls and DefaultsExplicit Variadic ArgumentsClosures and nonlocalRecap: Refactor a Pricing Tool8Composition and Inheritance
Collaborator Objectsextends and Method ResolutionInterfaces and Duck TypingValue Classes and DataclassesRecap: Notification Channels3Collections and References
Lists and Negative IndexesRecords and Tuple UnpackingMap Lookups and KeyErrorSets and Shared ObjectsRecap: Clean an Inventory6Reliable Python Programs
stdin and Exact Formattingon, catch, finally, and withLibraries and Import ExecutionStatic Types Versus HintsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler