Composition and Aliases
Lesson 38 of 48 in Coddy's Python for Rust Developers course.
Rust composition places one value inside another, often moving the contained value unless borrowed or cloned. Python composition usually stores references to supplied objects. The Bill example retains the same Rate object that the caller holds; changing that rate changes later totals. Rust can model shared ownership explicitly, but the example uses a cloned owned Rate to show an independent value. Decide which behavior the design needs before translating field assignments.
Rust excerpt inside main
#[derive(Clone)]
struct Rate { cents: i32 }
struct Bill { rate: Rate }
let mut rate = Rate { cents: 4 };
let bill = Bill { rate: rate.clone() };
rate.cents = 7;
println!("{} {}", bill.rate.cents * 2, rate.cents);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
Python storing a dependency does not make it immutable or exclusively owned. Document whether later caller mutation is supported, or copy the state you need.
Implement the specified API in the editable Python files. The locked driver.py runs the program and supplies input/output. Keep its imports and names unchanged.
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 Rust Developers
1From Rust to Python
Run Your First Python ProgramMacros to printBindings, mut, and ShadowingIntegers and Floor DivisionIndentation and ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Borrowed Iteration to forEntries and enumeratewhile, break, and continueIterators and ComprehensionsRecap: Build a Ranking2Values and Decisions
Option and NoneEquality and Object IdentityTruth Tests and FallbacksIf Expressions and elifRecap: Eligibility Rules5Functions and Closures
Functions and Shared ObjectsNamed Arguments and DefaultsPacking Calls and OptionsClosures and Capture TimingRecap: Refactor a Pricing Tool8Composition and Dispatch
Composition and AliasesInheritance Beyond TraitsTraits and Duck TypingDerived Equality and DataclassRecap: Notification Channels3Ownership and Collections
Vec to listTuples and DestructuringHashMap to dictClone and Shallow CopiesRecap: Clean an Inventory6Errors and Modules
Text Input and FormattingResult, Exceptions, and withModules and the Main GuardHints Without Borrow CheckingRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler