Injected Collaborators
Lesson 38 of 48 in Coddy's Python for Kotlin Developers course.
Kotlin constructor injection stores a collaborator, and Python can do the same with an instance attribute. Both languages share the passed object rather than clone it on assignment. A bill can delegate pricing to a rate object, keeping the policy separate from record processing. Python does not require a declared interface for that call, though the object must support the operation at runtime.
Kotlin
class Rate { fun cost(n: Int) = 7 * n }
class Bill(private val rate: Rate) { fun total(n: Int) = rate.cost(n) }
fun main() { println(Bill(Rate()).total(2)) }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
Passing a mutable collaborator shares its later changes with owners. If independent snapshots are required, make copying an explicit design choice.
Complete the task in its editable modules. The locked driver.py supplies execution; keep the required 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 Kotlin Developers
1From Kotlin to Python
Run Your First Python ProgramPrint and String TemplatesVal, Var, and Python NamesDivision and Integer WidthSuites and Block ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Ranges and Loop BindingsEntries and withIndexUpdates and Loop ControlCollection PipelinesRecap: Build a Ranking2Values and Decisions
Nullable Types and NoneEquality and IdentityBoolean Conditions and orIf Expressions and ElifRecap: Eligibility Rules5Functions and Closures
Functions and Shared ListsDefaults and Named CallsVararg and Keyword PackingClosures and Lambda ResultsRecap: Refactor a Pricing Tool8Composition and Dispatch
Injected CollaboratorsOpen Classes and superInterfaces and BehaviorData Classes and EqualityRecap: Notification Channels3Collections and Shared State
Read-only Lists and MutationPair and Tuple UnpackingMap Lookup and Missing KeysShallow Copies and SetsRecap: Clean an Inventory6Input, Errors, and Modules
Console Input and FormattingExceptions and Resource ScopeImports and Entry PointsStatic Types and AnnotationsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler