Composition Without Value Copy
Lesson 38 of 48 in Coddy's Python for C++ Developers course.
Composition lets one object delegate work to another. The C++ Bill shown owns a Rate member by value, copied from rate; changing the original does not change that member. Python self.rate = rate stores the supplied object reference. Updating that collaborator or assigning a replacement to bill.rate affects later delegated calls. This is closer to explicitly shared access in C++ than an embedded value member. Keep delegation visible instead of caching a calculated rate inside the bill.
C++17 excerpt: inside main
Standard-library headers are supplied in the runnable companion program.
struct Rate { int cents; int cost(int n) const { return cents * n; } };
struct Bill { Rate rate; int total(int n) const { return rate.cost(n); } };
Rate rate{4};
Bill bill{rate};
rate.cents = 7;
std::cout << bill.total(2) << '\n';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)
rate = Rate(4)
bill = Bill(rate)
rate.cents = 7
print(bill.total(2))Porting trap
The task driver can supply another object with cost(units). Do not construct a new concrete Rate inside total, because that discards the supplied collaborator.
Implement the task below in its editable Python modules. The locked driver.py supplies execution and checks. Keep the specified imports and API names.
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 C++ Developers
1From C++ to Python
Run Your First Python ProgramStreams to printNames, auto, and constDivision and Integer RangeBlocks and Name ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Range Loops and RebindingEntries and enumerateLoop Control Without ++Algorithms and ComprehensionsRecap: Build a Ranking2Values and Decisions
None, nullptr, and boolValues, Addresses, IdentityTruth Tests and OperandsBranches and Value SelectionRecap: Eligibility Rules5Functions, Calls, and Closures
Functions and Shared ObjectsDefaults and Named ArgumentsPacking and Unpacking CallsClosures and Capture TimingRecap: Refactor a Pricing Tool8Composition and Dispatch
Composition Without Value CopyInheritance and Method LookupVirtual Calls and Duck TypingEquality Beyond operator==Recap: Notification Channels3STL Habits and Python Objects
From vector to listTuples and Structured BindingsMaps, Keys, and OrderingValue Copies and Shared ListsRecap: Clean an Inventory6Errors, Resources, and Modules
Text Input and Exact OutputExceptions and RAIIModules Instead of HeadersHints Are Not Static TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler