Menu
CoddyTech

Collaborators Without Casts

Lesson 38 of 48 in Coddy's Python for Java Developers course.

Let an object delegate work to a collaborator it stores. Java commonly declares a field with an interface type and accepts an implementation in its constructor. Python can call the collaborator's method without declaring a common base class. The required behavior still matters: cost must accept units and return the promised result. Looking up self.rate during each total call allows the collaborator to be replaced later. This is composition, a has-a relationship, not inheritance.

Java excerpt: class member declarations

// Class members
interface Rate { int cost(int units); }
static class Bill {
    Rate rate;
    Bill(Rate rate) { this.rate = rate; }
    int total(int units) { return rate.cost(units); }
}

Python

class Bill:
    def __init__(self, rate):
        self.rate = rate
    def total(self, units):
        return self.rate.cost(units)

Watch the difference

Do not copy a collaborator's formula into its client or cache one computed total. Either choice bypasses future behavior changes. A missing cost method fails at runtime unless separate tooling catches the mismatch; duck typing is not automatic validation.

Practice

Apply this comparison in the task below. 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.

challenge icon

Challenge

Beginner

Implement 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 dependency injection through a Java interface, the bill must use the supplied behavior rather than duplicate 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))
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python for Java Developers

Practice on your own: Online Python compiler