Menu
CoddyTech

Receivers and Bound Methods

Lesson 34 of 48 in Coddy's Python for Kotlin Developers course.

Kotlin member methods have an implicit receiver available as this. Python ordinary methods spell the first parameter self, but a bound call supplies it automatically. Saving c.add retains the instance along with the function. Kotlin uses c::add for a bound function reference. In Python, calling c.add(3) does not require passing c again.

Kotlin

class Counter {
    var value = 0
    fun add(n: Int): Int { value += n; return value }
}
fun main() {
    val c = Counter()
    val add = c::add
    println("${add(3)} ${c.value}")
}

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

Omitting self from an instance-method definition shifts the arguments and leads to a call error. The word self is a convention, but the first-parameter role is required for ordinary bound methods.

Complete the task in its editable modules. The locked driver.py supplies execution; keep the required API names.

challenge icon

Challenge

Beginner

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

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

All lessons in Python for Kotlin Developers

Practice on your own: Online Python compiler