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
BeginnerImplement 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}")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for C# Developers
1C# Foundations in Python
Run the Python WorkspaceOutput, Strings, and CommentsTyped Locals to Python NamesDivision and RemaindersIndentation Instead of BracesRecap: Port a Receipt4Loops and Transformations
From foreach to forIndexes and Dictionary ItemsSentinels and Loop ControlFrom LINQ to ComprehensionsRecap: Stable Ranking7Objects and Properties
Instances Across ModulesInitialize Instance StateBound Methods and selfClass and Instance AttributesProperties and Access RulesRecap: Independent Accounts2None and Decisions
Nullable Values and NoneEquality, Identity, and TypesTruth Tests and FallbacksBranch PriorityRecap: Eligibility Rules3Collections and References
From List<T> to listTuples and UnpackingDictionary Keys and ValuesSets, Aliases, and CopiesRecap: Stock Lookup6Reliable Python Programs
Input and Exact OutputExceptions and ValidationImports and the Main GuardType Hints and Runtime TypesRecap: Validate a Batch9Project: Order Processor
Project 1: Order ModelProject 2: Pricing PoliciesPractice on your own: Online Python compiler