Store a Collaborator
Lesson 38 of 48 in Coddy's Python for R Developers course.
Composition gives one object a collaborator rather than making it inherit the collaborator's implementation. R lists and environments can store functions or other objects; Python stores collaborators as ordinary attributes. A bill can delegate pricing to a rate object with a cost method. No declared base class is required if the collaborator supports the needed call. Sharing a mutable collaborator means all owners observe its state changes, so choose independence deliberately. In this course, separate Python class modules make those responsibilities explicit. Do not flatten a collaborator into a one-time numeric result if later calls need to use changing arguments.
R
make_rate <- function(cents) list(cost=function(units) cents * units)
make_bill <- function(rate) list(total=function(units) rate$cost(units))
bill <- make_bill(make_rate(7))
cat(bill$total(2), "\n", sep="")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
Keep the API boundary clear: the bill owns delegation, and the rate owns the multiplication rule.
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 R Developers
1From R to Python
Run Your First Python Programcat, print, and StringsBindings and Copy SemanticsInteger Arithmetic and NABraces Become SuitesRecap: Rewrite a Receipt4Iteration and Transformations
seq_along and rangeitems and enumeratenext and continuelapply and ComprehensionsRecap: Build a Ranking2Values and Decisions
NULL, NA, and NoneVector Equality and IdentityScalar Conditions, Not Vectorsifelse and Scalar SelectionRecap: Eligibility Rules5Functions and Environments
Explicit Function ReturnsLazy and Eager DefaultsDots Versus Star ArgumentsEnvironments and nonlocalRecap: Refactor a Pricing Tool8Composition and Dispatch
Store a CollaboratorNextMethod and superGenerics to Duck TypingRecords and Generated EqualityRecap: Notification Channels3Vectors to Containers
Vectors, Lists, and Index ZeroTuples and Exact UnpackingNamed Lists and Dictionariesunique and Shallow CopiesRecap: Clean an Inventory6Reliable Python Programs
readLines and Text ContractsConditions and Cleanupsource and Module ImportsAnnotations and Runtime TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler