self and Method References
Lesson 34 of 48 in Coddy's Python for Swift Developers course.
Swift method references and Python bound methods can both retain the receiver they operate on. Python spells self explicitly as the first method parameter, but normal method calls supply it automatically. Saving counter.add creates a callback that remembers the same object. The callback's mutation is visible through counter afterward. Python has no mutating marker or inout exclusivity enforcement on that method, so API contracts should make side effects clear.
Swift example
final class Counter {
var value = 0
func add(_ amount: Int) -> Int { value += amount; return value }
}
let counter = Counter()
let callback = counter.add
print(callback(3), counter.value)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
Calling an already bound Python method with self again duplicates the receiver and misbinds arguments.
Implement the specified API in the editable Python files. The locked driver.py runs the program and supplies input/output. Keep its imports and names unchanged.
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 Swift Developers
1From Swift to Python
Run Your First Python ProgramPrinting and Stringslet, var, and RebindingInt Range and DivisionIndentation and Block ScopeRecap: Rewrite a Receipt4Iteration and Transformations
for and Half-Open Rangesenumerated to enumeratewhile and Loop Controlmap, filter, ComprehensionsRecap: Build a Ranking7Instances and Shared State
Structs and Dynamic Attributesinit to __init__self and Method ReferencesType Properties and ShadowingComputed Properties and TextRecap: Model a Bank Account2Values and Decisions
Optionals and NoneEquatable and IdentityBool Conditions and FallbacksBranches and TernariesRecap: Eligibility Rules3Value Types to Shared Objects
Array to listTuples and UnpackingDictionary Lookup and OrderValue Copies and AliasesRecap: Clean an Inventory6Errors and Modules
Input and String Formattingthrows, defer, and withModules and Main GuardsHints and Runtime TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler