This and Bound Methods
Lesson 34 of 48 in Coddy's Python for PHP Developers course.
PHP methods access the current instance through $this. Python instance methods receive it as their first parameter, conventionally self. Calling counter.add(3) automatically supplies counter as that first argument. Saving counter.add saves a bound method that retains the instance. PHP can form a callable with an object and a method name; Python's bound-method value is directly callable.
PHP 8.3
<?php
class Counter {
public $value = 0;
public function add($n) { $this->value += $n; return $this->value; }
}
$c = new Counter();
$add = [$c, 'add'];
echo $add(3), ' ', $c->value, "\n";Python
class Counter:
def __init__(self):
self.value = 0
def add(self, n):
self.value += n
return self.value
c = Counter()
add = c.add
print(add(3), c.value)Porting trap
Do not pass self again when calling a bound method, and do not omit it from an ordinary instance-method definition. Python does not inject a hidden $this name into the function body.
Complete the task in the editable Python files. Keep the required function and class names; the locked driver.py supplies execution.
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 PHP Developers
1From PHP to Python
Run Your First Python ProgramEcho, Strings, and printVariables Without Dollar SignsDivision and Numeric TextIndentation and SuitesRecap: Rewrite a Receipt4Iteration and Transformations
Foreach and rangeKeys, Items, and enumerateWhile Without IncrementFilters and Sort KeysRecap: Build a Ranking7Instances and Shared State
Instances Without newConstructors and Fresh ListsThis and Bound MethodsStatic and Instance AttributesProperties and Object TextRecap: Model a Bank Account2Values and Decisions
Null, None, and Missing KeysStrict Equality Is Not isThe Zero String TrapElif and Value SelectionRecap: Eligibility Rules3Arrays and Python Collections
PHP Arrays and Python ListsDestructuring and TuplesKeys, Null, and getArray Copies and List AliasesRecap: Clean an Inventory6Input, Errors, and Modules
CLI Input and Exact OutputConversion Errors and CleanupImports Instead of requireType Hints Are Not PHP TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler