Interface Fields and Calls
Lesson 38 of 48 in Coddy's Python for Go Developers course.
A Go struct can store an interface-valued collaborator, letting implementations vary. A Python object can store a collaborator and call the required method without declaring an interface field type. The bill owns orchestration and the rate owns pricing. Looking up the current collaborator each time lets replacement affect later calls. Copying its formula into the bill would break that separation and reject unfamiliar but compatible policies.
Go
Go excerpt: declarations above main, statements inside main. Imports: fmt. The verification bundle contains the complete program.
type Pricer interface { Cost(int) int }
type Rate struct { Cents int }
func (r Rate) Cost(units int) int { return r.Cents * units }
type Bill struct { Rate Pricer }
func (b Bill) Total(units int) int { return b.Rate.Cost(units) }
// Inside main:
b := Bill{Rate: Rate{Cents: 4}}
fmt.Println(b.Total(3))
b.Rate = Rate{Cents: 7}
fmt.Println(b.Total(3))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)
b = Bill(Rate(4))
print(b.total(3))
b.rate = Rate(7)
print(b.total(3))Porting trap
Do not require a particular class name when the contract only requires cost(units). Python type hints can describe a protocol, but ordinary duck-typed calls work without a shared base class.
Challenge
BeginnerImplement Rate(cents).cost(units) as multiplication, and UsageBill(rate).total(units) by delegating to its stored current rate.cost(units). The driver reads rate, units, replacement rate, and bonus (nonnegative integers), prints the first total, replaces the collaborator with an object computing replacement_rate * units + bonus, and prints again. As with a Go interface-valued field, delegate to the current collaborator rather than copying its formula.
Editable files: rate.py, usage_bill.py. Keep the provided imports and the required API names. The locked driver.py supplies execution and checks; do not edit it.
Implement the named definitions in the editable modules without input or printing. The driver owns input/output and may call the APIs again on fresh data without producing extra output.
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 Go Developers
1From Go to Python
Run Your First Python ProgramPrinting, Quotes, and CommentsBindings Beyond Go TypesDivision and Growing IntegersIndentation and ScopeRecap: A Python Receipt4Iteration and Transformations
range and Value IterationIndexes and Map EntriesSentinels Without Truth TrapsComprehensions and Stable SortRecap: Stable Ranking2Values, Absence, and Branches
None, nil, and Zero ValuesEquality Is Not IdentityTruth Tests Beyond boolBranches and Value SelectionRecap: Missing or Eligible5Functions and Call Contracts
Functions and Tuple ReturnsDefaults and Named ArgumentsVariadics and Keyword OptionsClosures and Callable ValuesRecap: Pricing Functions8Interfaces and Object Design
Interface Fields and CallsEmbedding Is Not InheritanceInterfaces and Duck TypingStructs and Data ClassesRecap: Pluggable Channels3Slices, Maps, and Sharing
Slices Versus Python ListsMultiple Values and TuplesGo Maps and Python dictsSets and Shallow CopiesRecap: Inventory Collections6Errors, Modules, and Hints
Text and Exact OutputErrors Versus ExceptionsPackages and Module ExecutionHints Versus Static TypesRecap: Validate a Batch9Project: An Order Processor
Project: Model an OrderProject: Pricing PoliciesPractice on your own: Online Python compiler