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
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. 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}")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for Java Developers
1From Java Classes to Python
Run Python Without a ClassPrinting Text and CommentsBindings, Types, and finalDivision and Numeric TypesIndentation Defines BlocksRecap: A Python Receipt4Iteration and Transformations
Enhanced Loops and rangeIndexes and Map EntriesSentinels and Loop ControlFrom Streams to ComprehensionsRecap: Stable Ranking7Instance and Class State
Instances Without newInitializing Instance StateBound Methods and selfClass State Is Not a FieldProperties and Access ControlRecap: Account State2Values Beyond Java Primitives
None and Boolean ValuesValue Equality and IdentityTruth Tests Beyond booleanBranches and Value SelectionRecap: Missing or Eligible3Collections and Object Sharing
Lists and ArrayList HabitsTuples Without Record ClassesDictionaries and Java MapsShared References and CopiesRecap: Inventory Collections6Contracts, Errors, and Modules
Text Input and Exact OutputValueError and TypeErrorModules Versus Utility ClassesAnnotations Are Not Java TypesRecap: Validate a Batch9Project: An Order Processor
Project: Model an OrderProject: Pricing PoliciesPractice on your own: Online Python compiler