Receivers and Bound Methods
Lesson 34 of 48 in Coddy's Python for Go Developers course.
A Go method declares its receiver separately; a pointer receiver can update the caller's struct. Python instance methods conventionally name their first parameter self. Accessing c.add produces a bound method that remembers c, so f(3) supplies self automatically. This resembles a Go method value such as c.Add. Python self is an ordinary parameter name by convention, not a receiver keyword.
Go
Go excerpt: declarations above main, statements inside main. Imports: fmt. The verification bundle contains the complete program.
type Counter struct { Value int }
func (c *Counter) Add(n int) int { c.Value += n; return c.Value }
// Inside main:
c := Counter{Value: 2}
f := c.Add
fmt.Println(f(3))
fmt.Println(c.Value)Python
class Counter:
def __init__(self, value):
self.value = value
def add(self, amount):
self.value += amount
return self.value
c = Counter(2)
f = c.add
print(f(3))
print(c.value)Porting trap
Go value receivers copy the receiver value; Python has no automatic value-receiver copy. Mutating self.value updates the shared instance. Do not pass c a second time when calling a bound method.
Challenge
BeginnerImplement Counter(start) with integer value and add(amount), which updates and returns value. The driver reads start and a possibly empty line of integer changes, saves counter.add as a bound callback, and prints each returned result followed by final:value. Changes may be negative. As with a Go method value on a pointer receiver, the bound Python callback retains its receiver and mutates its state.
Editable files: counter.py. Keep the provided imports and the required API names. The locked driver.py supplies execution and checks; do not edit it.
Implement the named definitions in the editable modules without input or printing. The driver owns input/output and may call the APIs again on fresh data without producing extra output.
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 Go Developers
1From Go to Python
Run Your First Python ProgramPrinting, Quotes, and CommentsBindings Beyond Go TypesDivision and Growing IntegersIndentation and ScopeRecap: A Python Receipt4Iteration and Transformations
range and Value IterationIndexes and Map EntriesSentinels Without Truth TrapsComprehensions and Stable SortRecap: Stable Ranking7Structs to Python Classes
From Structs to InstancesInitialization and Fresh StateReceivers and Bound MethodsClass State and ShadowingProperties and Display HooksRecap: Account State2Values, Absence, and Branches
None, nil, and Zero ValuesEquality Is Not IdentityTruth Tests Beyond boolBranches and Value SelectionRecap: Missing or Eligible3Slices, Maps, and Sharing
Slices Versus Python ListsMultiple Values and TuplesGo Maps and Python dictsSets and Shallow CopiesRecap: Inventory Collections6Errors, Modules, and Hints
Text and Exact OutputErrors Versus ExceptionsPackages and Module ExecutionHints Versus Static TypesRecap: Validate a Batch9Project: An Order Processor
Project: Model an OrderProject: Pricing PoliciesPractice on your own: Online Python compiler