self and Bound Methods
Lesson 34 of 48 in Coddy's Python for Rust Developers course.
Rust methods distinguish self, &self, and &mut self in the receiver type. Python conventionally writes self as the first instance-method parameter without a mutability qualifier. Calling counter.add(3) supplies the receiver automatically. Reading counter.add produces a bound method that remembers the object; it can be saved and called later. Python does not enforce an exclusive borrow while a callback retains that object, so shared mutation must be managed by design.
Rust excerpt inside main
struct Counter { value: i32 }
impl Counter {
fn add(&mut self, amount: i32) -> i32 { self.value += amount; self.value }
}
let mut counter = Counter { value: 0 };
let mut callback = |n| counter.add(n);
let result = callback(3);
println!("{} {}", result, counter.value);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)Porting trap
Do not omit self in a Python instance method. The implicit receiver then occupies the first declared argument and can cause an argument-count failure.
Implement the specified API in the editable Python files. The locked driver.py runs the program and supplies input/output. Keep its imports and names unchanged.
Challenge
BeginnerImplement 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}")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for Rust Developers
1From Rust to Python
Run Your First Python ProgramMacros to printBindings, mut, and ShadowingIntegers and Floor DivisionIndentation and ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Borrowed Iteration to forEntries and enumeratewhile, break, and continueIterators and ComprehensionsRecap: Build a Ranking7Instances and Shared State
Structs to InstancesInitialization and Ownershipself and Bound MethodsClass and Instance StateProperties and DisplayRecap: Model a Bank Account2Values and Decisions
Option and NoneEquality and Object IdentityTruth Tests and FallbacksIf Expressions and elifRecap: Eligibility Rules3Ownership and Collections
Vec to listTuples and DestructuringHashMap to dictClone and Shallow CopiesRecap: Clean an Inventory6Errors and Modules
Text Input and FormattingResult, Exceptions, and withModules and the Main GuardHints Without Borrow CheckingRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler