this and Bound Methods
Lesson 34 of 48 in Coddy's Python for Dart Developers course.
Dart instance methods have an implicit receiver accessible as this, and field access can often omit that prefix. Python methods explicitly declare self and use it to access instance attributes. A normal dotted method call binds self automatically, so callers supply only the other arguments. Both languages support method tear-offs or bound method values that retain their receiver. This lets a callback update the same instance after it is stored elsewhere. In Python, an unqualified name is not automatically resolved as an instance field. Return the promised result explicitly after mutation when the API requires it.
Dart
class Counter {
int value = 1;
int add(int amount) => value += amount;
}
void main() {
final counter = Counter();
final callback = counter.add;
print(callback(2));
print(counter.value);
}Python
class Counter:
def __init__(self):
self.value = 1
def add(self, amount):
self.value += amount
return self.value
counter = Counter()
callback = counter.add
print(callback(2))
print(counter.value)Porting trap
Do not pass the receiver twice to an already-bound Python method, and do not omit self when accessing its fields.
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 Dart Developers
1From Dart to Python
Run Your First Python ProgramInterpolation and printvar, final, and Python NamesFloor Versus TruncationBraces and Block ScopeRecap: Rewrite a Receipt4Iteration and Transformations
for-in and rangeentries and enumerateLoop Updates and continuewhere, map, and List BuildingRecap: Build a Ranking7Objects and Shared State
Declared Fields and AttributesConstructors and __init__this and Bound MethodsClass Fields and LookupGetters, Setters, and __str__Recap: Model a Bank Account2Values and Decisions
Null Safety and NoneList Equality ChangesConditions and Null DefaultsTernaries and elifRecap: Eligibility Rules3Collections and References
Lists and Negative IndexesRecords and Tuple UnpackingMap Lookups and KeyErrorSets and Shared ObjectsRecap: Clean an Inventory6Reliable Python Programs
stdin and Exact Formattingon, catch, finally, and withLibraries and Import ExecutionStatic Types Versus HintsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler