Sharing Collaborators
Lesson 38 of 48 in Coddy's Python for PHP Developers course.
Composition stores a collaborator rather than inheriting its implementation. PHP object assignment copies an object identifier, so both variables can refer to one object; Python names similarly share an object after assignment. Inject a rate or policy into a bill and call its method when needed. This differs from PHP array value copying: replacing a variable and mutating the referenced object are separate operations.
PHP 8.3
<?php
class Rate { public $cents = 7; public function cost($n) { return $this->cents * $n; } }
class Bill {
public $rate;
public function __construct($rate) { $this->rate = $rate; }
public function total($n) { return $this->rate->cost($n); }
}
echo (new Bill(new Rate()))->total(2), "\n";Python
class Rate:
def cost(self, n):
return 7 * n
class Bill:
def __init__(self, rate):
self.rate = rate
def total(self, n):
return self.rate.cost(n)
print(Bill(Rate()).total(2))Porting trap
If two owners must have independent collaborator state, constructing or copying that collaborator is a design decision. Assignment alone does not clone the object in either language.
Complete the task in the editable Python files. Keep the required function and class names; the locked driver.py supplies execution.
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 PHP Developers
1From PHP to Python
Run Your First Python ProgramEcho, Strings, and printVariables Without Dollar SignsDivision and Numeric TextIndentation and SuitesRecap: Rewrite a Receipt4Iteration and Transformations
Foreach and rangeKeys, Items, and enumerateWhile Without IncrementFilters and Sort KeysRecap: Build a Ranking2Values and Decisions
Null, None, and Missing KeysStrict Equality Is Not isThe Zero String TrapElif and Value SelectionRecap: Eligibility Rules5Functions and Closures
Functions and Mutable InputsNamed Calls and Default StateVariadics and Call UnpackingArrow Capture and Late BindingRecap: Refactor a Pricing Tool8Composition and Dispatch
Sharing CollaboratorsParent Calls and superInterfaces and Duck TypingEquality and DataclassesRecap: Notification Channels3Arrays and Python Collections
PHP Arrays and Python ListsDestructuring and TuplesKeys, Null, and getArray Copies and List AliasesRecap: Clean an Inventory6Input, Errors, and Modules
CLI Input and Exact OutputConversion Errors and CleanupImports Instead of requireType Hints Are Not PHP TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler