Menu
CoddyTech

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 icon

Challenge

Beginner

Implement 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}")
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