Menu
CoddyTech

Callbacks to Composition

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

A C struct can hold a function pointer as a behavior slot, optionally paired with a context pointer. Python composition stores a collaborator object and invokes its method. Bill should delegate to its current policy rather than copy the pricing formula or construct a replacement. This lets a caller replace the collaborator while preserving the same bill. There is no required shared base class when objects already provide the method the consumer needs.

C: complete example.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
struct Policy { int (*cost)(int); };
int double_cost(int units) { return units * 2; }
int bill(const struct Policy *p, int units) { return p->cost(units); }
int main(void) {
    struct Policy p = {double_cost};
    printf("%d\n", bill(&p, 4));
    return 0;
}

Python: complete example.py

class DoublePolicy:
    def cost(self, units):
        return units * 2
class Bill:
    def __init__(self, policy):
        self.policy = policy
    def total(self, units):
        return self.policy.cost(units)
print(Bill(DoublePolicy()).total(4))

Watch the difference

Avoid caching the initial method if the contract permits replacement of the whole collaborator. Reading self.policy.cost when total runs observes the current policy. Ownership and mutation still matter even though Python manages allocation.

Your code goes in rate.py, usage_bill.py. The locked driver.py is the entry file, supplies execution and checks, and cannot be edited.

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.

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.

Delegate through the current collaborator, as a C design would invoke the supplied behavior slot rather than hard-code its implementation.

Your code goes in rate.py, usage_bill.py. The locked driver.py is the entry file, supplies execution and checks, and cannot be edited.

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 C Developers

Practice on your own: Online Python compiler