Replaceable Collaborators
Lesson 38 of 48 in Coddy's Python for C# Developers course.
Delegate to a collaborator that can be replaced.
C# reference excerpt
Executable statements use C# top-level program style; type-only examples are declarations. System names assume the usual using System directive.
interface IRate { int Cost(int units); }
class Bill {
public IRate Rate;
public Bill(IRate rate) { Rate = rate; }
public int Total(int units) => Rate.Cost(units);
}Python
class Bill:
def __init__(self, rate):
self.rate = rate
def total(self, units):
return self.rate.cost(units)What changes
C# commonly declares a collaborator interface. This Python class calls the supplied object by behavior without requiring an interface declaration. Store the collaborator and delegate at call time so replacement changes later results. The bill owns coordination; the rate owns its pricing calculation. Imports organize implementations without forcing a shared base class.
Transfer mistake
Do not copy the collaborator formula into Bill or cache its initial result. A different object with a cost method may implement a different formula and still satisfy the expected behavior.
Your task
Implement Rate(cents) with cost(units) returning cents * units. Implement UsageBill(rate) storing the collaborator as rate and total(units) delegating to its current cost method. The driver reads rate, units, replacement rate, and bonus as four nonnegative integers. It prints the original total, replaces the collaborator with a supplied object computing replacement_rate * units + bonus, then prints the new total.
Challenge
BeginnerImplement Rate(cents) with cost(units) returning cents * units. Implement UsageBill(rate) storing the collaborator as rate and total(units) delegating to its current cost method. The driver reads rate, units, replacement rate, and bonus as four nonnegative integers. It prints the original total, replaces the collaborator with a supplied object computing replacement_rate * units + bonus, then prints the new total.
Editable implementation files: rate.py, usage_bill.py. The locked driver.py is the supplied launcher or input/output harness and must remain unchanged.
Keep the supplied imports and exact API names. Return results or raise the required exceptions; do not read input or print from these implementation 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
1C# Foundations in Python
Run the Python WorkspaceOutput, Strings, and CommentsTyped Locals to Python NamesDivision and RemaindersIndentation Instead of BracesRecap: Port a Receipt4Loops and Transformations
From foreach to forIndexes and Dictionary ItemsSentinels and Loop ControlFrom LINQ to ComprehensionsRecap: Stable Ranking2None and Decisions
Nullable Values and NoneEquality, Identity, and TypesTruth Tests and FallbacksBranch PriorityRecap: Eligibility Rules5Functions and Scope
Define Functions and ReturnNamed Arguments and DefaultsStar Arguments and UnpackingCallbacks and Python ScopeRecap: Pricing Functions8Composition and Inheritance
Replaceable CollaboratorsOverrides and superInterfaces and Duck TypingRecords and Value EqualityRecap: Dispatch by Behavior3Collections and References
From List<T> to listTuples and UnpackingDictionary Keys and ValuesSets, Aliases, and CopiesRecap: Stock Lookup6Reliable Python Programs
Input and Exact OutputExceptions and ValidationImports and the Main GuardType Hints and Runtime TypesRecap: Validate a Batch9Project: Order Processor
Project 1: Order ModelProject 2: Pricing PoliciesPractice on your own: Online Python compiler