this and Bound Methods
Lesson 34 of 48 in Coddy's Python for C++ Developers course.
C++ member functions receive an implicit this pointer. A Python instance method declares an explicit first parameter, conventionally self. counter.add(3) supplies counter automatically; Counter.add(counter, 3) expresses the same ordinary call explicitly. Saving callback = counter.add creates a bound method retaining the instance. A C++ pointer-to-member alone does not bind an object; the example uses a lambda to supply one.
C++17 excerpt: inside main
Standard-library headers are supplied in the runnable companion program.
struct Counter {
int value = 0;
int add(int amount) { value += amount; return value; }
};
Counter counter;
auto callback = [&counter](int x) { return counter.add(x); };
int result = callback(3);
std::cout << result << ' ' << counter.value << '\n';Python
class Counter:
def __init__(self):
self.value = 0
def add(self, amount):
self.value += amount
return self.value
counter = Counter()
callback = counter.add
print(callback(3), counter.value)Porting trap
Inside Python methods, write self.value to read or mutate instance state. value without self is a different name lookup, not implicit member access.
Implement the task below in its editable Python modules. The locked driver.py supplies execution and checks. Keep the specified imports and API names.
Challenge
BeginnerImplement Counter(start) with integer attribute value and method add(amount). The method increases value and returns the new value. Input has a starting integer and a line of space-separated integer changes (possibly empty). The driver saves counter.add as a callback, calls it for each change, prints each returned value on its own line, and finally prints final:value. Negative changes are allowed.
The locked driver reads input and prints results. Submit the required class and function definitions only; do not read input or print in your solution. Keep the API names exactly as specified.
Your code goes in the editable files counter.py. driver.py holds the supplied input/output code and API checks and cannot be edited. Keep the supplied imports; do not read input or print from the editable 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
1From C++ to Python
Run Your First Python ProgramStreams to printNames, auto, and constDivision and Integer RangeBlocks and Name ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Range Loops and RebindingEntries and enumerateLoop Control Without ++Algorithms and ComprehensionsRecap: Build a Ranking7Instances and Shared State
Instances Without newInitialization and Ownershipthis and Bound MethodsShared and Instance StateProperties and Object TextRecap: Model a Bank Account2Values and Decisions
None, nullptr, and boolValues, Addresses, IdentityTruth Tests and OperandsBranches and Value SelectionRecap: Eligibility Rules3STL Habits and Python Objects
From vector to listTuples and Structured BindingsMaps, Keys, and OrderingValue Copies and Shared ListsRecap: Clean an Inventory6Errors, Resources, and Modules
Text Input and Exact OutputExceptions and RAIIModules Instead of HeadersHints Are Not Static TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler