Callable and Bound Methods
Lesson 34 of 48 in Coddy's Python for GDScript Developers course.
GDScript methods use an implicit self and may be stored as Callables. Python instance methods declare self explicitly, but a bound call supplies it automatically. Saving c.add retains the instance; invoke the saved method as add(3), without a Godot call method. Both examples mutate the same stored counter object through the bound operation.
GDScript
extends SceneTree
class Counter extends RefCounted:
var value = 0
func add(n):
value += n
return value
func _init():
var c = Counter.new()
var add = c.add
prints(add.call(3), c.value)
quit()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 invoking a bound Python method. Python Callable values are not Godot Callable objects with bind, callv, and signal-connection APIs.
Complete the task in its editable modules. The locked driver.py supplies execution; keep the required 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 GDScript Developers
1From GDScript to Python
Run Your First Python ProgramPrint Is Not printsVar, Const, and BindingsInteger Division DifferencesSimilar Indentation, New ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Ranges and RebindingItems and enumerateWhile and Early ExitArray Callbacks and KeysRecap: Build a Ranking7Instances and Shared State
New and Python Class CallsInit and Per-instance ListsCallable and Bound MethodsStatic and Instance StateSetters and Printable ObjectsRecap: Model a Bank Account2Values and Decisions
Null and NoneThe is Keyword Changes MeaningLogical Results and OperandsConditional ExpressionsRecap: Eligibility Rules3Collections and Shared State
Array and List APIsArrays, Vectors, and TuplesDictionary Lookup RulesDuplicate and Shallow CopyRecap: Clean an Inventory6Input, Errors, and Modules
Console Work Outside GodotValidation and ExceptionsScript Resources and ImportsTyped GDScript and AnnotationsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler