Menu
CoddyTech

Methods and self

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

Write methods that update the instance on which they are called, and pass a bound method as a callback when another part of your program needs that behavior later.

JavaScript

class Bell {
  constructor() { this.count = 0; }
  ring() { this.count += 1; return this.count; }
}
const bell = new Bell();
const ring = bell.ring.bind(bell);
console.log(ring(), ring());

Python

class Bell:
    def __init__(self):
        self.count = 0
    def ring(self):
        self.count += 1
        return self.count
bell = Bell()
ring = bell.ring
print(ring(), ring())

What changes

Both complete programs print 1 2. An ordinary Python instance method declares an explicit first parameter, conventionally self. Accessing it through an instance produces a bound method that remembers that instance. Saving bell.ring therefore preserves its receiver. Calling bell.ring() supplies bell automatically, and the explicit form Bell.ring(bell) calls the same method for this class. JavaScript regular methods use this according to how they are called; the example binds it before extracting the callback.

Common mistake

Do not translate this into a special Python keyword. self is an ordinary parameter name, used consistently by convention. Also distinguish updating state from returning a result: a method without an explicit return still returns None, even if it changes an attribute successfully.

Your task

Implement a counter method whose return value reflects its updated state. The driver saves the bound method and invokes it repeatedly, including with negative changes.

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

Practice on your own: Online Python compiler