Menu
CoddyTech

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 icon

Challenge

Beginner

Implement 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}")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python for Go Developers

Practice on your own: Online Python compiler