Bound Methods Versus Callbacks
Lesson 34 of 48 in Coddy's Python for C Developers course.
A C callback that modifies a struct commonly receives an explicit pointer to the struct along with its operation arguments. Python methods declare self as an ordinary first parameter, but accessing c.add produces a bound method that remembers c. Calling the saved callback with just the amount supplies the receiver automatically. Counter.add(c, 3) is the corresponding explicit class-level call. Saving a bound method retains its receiver even after the original variable is rebound.
C: complete example.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
struct Counter { int value; };
int add(struct Counter *self, int amount) { self->value += amount; return self->value; }
int main(void) {
struct Counter c = {2};
int (*callback)(struct Counter *, int) = add;
printf("%d\n", callback(&c, 3));
return 0;
}Python: complete example.py
class Counter:
def __init__(self, value):
self.value = value
def add(self, amount):
self.value += amount
return self.value
c = Counter(2)
callback = c.add
print(callback(3))Watch the difference
Do not pass self twice to a bound method. Calling callback(c, 3) supplies too many arguments for this definition. Do not omit self from the method declaration either.
Your code goes in counter.py. The locked driver.py is the entry file, supplies execution and checks, and cannot be edited.
Challenge
BeginnerImplement Counter(start) with integer value and add(amount), which updates and returns value. The driver reads start and a possibly empty line of integer changes, saves counter.add as a bound callback, and prints each returned result followed by final:value. Changes may be negative.
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.
The bound method retains its receiver, replacing the explicit context-pointer argument common in C callbacks.
Your code goes in counter.py. The locked driver.py is the entry file, supplies execution and checks, and cannot be edited.
Try it yourself
from counter import Counter
counter = Counter(int(input()))
changes = [int(x) for x in input().split()]
callback = counter.add
for amount in changes:
print(callback(amount))
print(f"final:{counter.value}")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for C Developers
1From C Programs to Python
Run Python Without mainPrinting Without Format CodesNames Versus Typed StorageDivision and Integer LimitsSuites Instead of BracesRecap: A Python Receipt4Iteration and Transformations
Iteration Without PointersIndexes Without Pointer MathSentinels and Loop ControlComprehensions and SortingRecap: Stable Ranking7Structs to Python Objects
Allocation and Object LifetimeInitializing Object StateBound Methods Versus CallbacksShared State and ShadowingProperties and Validated StateRecap: Account State2Values and Truth Tests
Absence Is Not a Null PointerContent Versus Object IdentityTruth Tests and OperandsConditional Value SelectionRecap: Missing or Eligible3Containers and Aliasing
Lists Versus C ArraysTuples and Struct ValuesMappings and Lookup LoopsPointers, Copies, and AliasesRecap: Inventory Collections6Contracts, Errors, and Modules
Text Input and Exact OutputError Codes Versus ExceptionsImports Are Not IncludesAnnotations Versus C TypesRecap: Validate a Batch9Project: An Order Processor
Project: Model an OrderProject: Pricing PoliciesPractice on your own: Online Python compiler