Colon Calls to Bound Methods
Lesson 34 of 48 in Coddy's Python for Lua Developers course.
Lua colon-call syntax passes the table as the first argument: obj:method(x) behaves like obj.method(obj, x). Merely reading obj.method gives a function without automatically binding the receiver. Python instance method access creates a bound method, so saving counter.add preserves the receiver. The first parameter is conventionally self and must still be declared. Calling the saved callback later mutates the same instance, not a copied field snapshot.
Lua example
local counter = {value = 0}
function counter:add(n) self.value = self.value + n; return self.value end
local callback = counter.add
local result = callback(counter, 3)
print(result .. " " .. 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
Do not pass the receiver a second time to an already bound Python method, or the call receives too many 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 Lua Developers
1From Lua to Python
Run Your First Python ProgramPrinting and TextNames and Local ScopeNumbers and ConversionSuites Instead of endRecap: Rewrite a Receipt4Iteration and Transformations
Numeric for to rangepairs, ipairs, and itemsLoop Control and SkipsComprehensions and SortingRecap: Build a Ranking7Classes Beyond Metatables
Tables to Class InstancesConstructors and Fresh StateColon Calls to Bound MethodsLookup and Shared DefaultsProperties and tostringRecap: Model a Bank Account2Values and Decisions
nil Versus NoneTable Identity and EqualityTruthiness Is Differentelif and Value SelectionRecap: Eligibility Rules3Tables to Typed Collections
Sequence Tables to ListsTuples and Multiple ReturnsRecords to DictionariesSets and Shared TablesRecap: Clean an Inventory6Errors and Modules
Input and Exact Textpcall to Exceptionsrequire to importHints and Runtime TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler