Menu
CoddyTech

Bound Methods and self

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

Use a bound method as a callback on its original receiver.

C# reference excerpt

Executable statements use C# top-level program style; type-only examples are declarations. System names assume the usual using System directive.

var counter = new Counter();
Action<int> change = counter.Add;
change(3);
Console.WriteLine(counter.Value);
class Counter { public int Value; public void Add(int n) { Value += n; } }

Python

class Counter:
    def __init__(self):
        self.value = 0
    def add(self, n):
        self.value += n

counter = Counter()
change = counter.add
change(3)
print(counter.value)

What changes

Python instance methods spell out self in the definition; callers omit it because a bound method supplies the instance. Saving counter.add retains its receiver, conceptually like a C# instance-method delegate. self is a convention, not a reserved keyword, but following it makes methods recognizable. Return values remain separate from mutations.

Transfer mistake

counter.add(counter, 3) supplies the instance twice. Omitting self from the definition also shifts the received arguments incorrectly. Keep methods reusable by leaving input/output to the locked driver.

Your task

Implement Counter(start) with instance attribute value. Its add(amount) method updates value and returns the new integer. Input is a starting integer and a space-separated line of integer changes, possibly empty. The driver saves a bound method, applies every change, prints its returned value after each call, and prints final:value last. Negative changes are valid.

challenge icon

Challenge

Beginner

Implement Counter(start) with instance attribute value. Its add(amount) method updates value and returns the new integer. Input is a starting integer and a space-separated line of integer changes, possibly empty. The driver saves a bound method, applies every change, prints its returned value after each call, and prints final:value last. Negative changes are valid.

Editable implementation files: counter.py. The locked driver.py is the supplied launcher or input/output harness and must remain unchanged.

Keep the supplied imports and exact API names. Return results or raise the required exceptions; do not read input or print from these implementation modules.

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