Menu
CoddyTech

Bound Methods and self

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

Use explicit self in a method definition and omit it in an ordinary instance call. counter.add(3) binds counter to self. Retrieving counter.add creates a bound method retaining its receiver, so a saved callback updates the same instance. Java can express receiver-bound behavior through counter::add assigned to a functional interface; Python needs no interface declaration for this callback. Return the updated value when the caller needs it, rather than printing inside a reusable model.

Java excerpt: class member declarations

// Class member
static class Counter {
    int value;
    int add(int amount) { return value += amount; }
}

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)

Watch the difference

Defining add(amount) without self shifts argument binding and usually raises TypeError when called on an instance. A bare value name is not shorthand for self.value. Python does not implicitly search instance fields for local names.

Practice

Apply this comparison in the task below. 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.

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. This bound Python method serves a role similar to a Java receiver-bound method reference.

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 Java Developers

Practice on your own: Online Python compiler