Receiver Methods and Generics
Lesson 34 of 48 in Coddy's Python for R Developers course.
R S3 commonly dispatches a generic function based on the class of an argument. Python ordinary methods are looked up on a receiver and bind that receiver as self. Declare self explicitly as the first method parameter, but omit it when calling the bound method through an instance. This is closer in appearance to reference-object methods than to a free-standing S3 generic. A bound Python method retains the receiver when saved as a callback. Explicitly return a value if the API requires one; attribute mutation alone does not create an implicit function result as an R final expression can.
R
counter <- new.env(parent=emptyenv())
counter$value <- 1
add <- function(object, amount) {
object$value <- object$value + amount
object$value
}
cat(add(counter, 2), "\n", sep="")
cat(counter$value, "\n", sep="")Python
class Counter:
def __init__(self):
self.value = 1
def add(self, amount):
self.value += amount
return self.value
counter = Counter()
callback = counter.add
print(callback(2))
print(counter.value)Porting trap
Do not supply self a second time when invoking an already-bound method. The remaining parameters are the ones the caller provides.
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 R Developers
1From R to Python
Run Your First Python Programcat, print, and StringsBindings and Copy SemanticsInteger Arithmetic and NABraces Become SuitesRecap: Rewrite a Receipt4Iteration and Transformations
seq_along and rangeitems and enumeratenext and continuelapply and ComprehensionsRecap: Build a Ranking7Objects and Shared State
R Objects and Python ClassesInitializing Instance StateReceiver Methods and GenericsClass Lookup and Shared ListsValidated Attribute AccessRecap: Model a Bank Account2Values and Decisions
NULL, NA, and NoneVector Equality and IdentityScalar Conditions, Not Vectorsifelse and Scalar SelectionRecap: Eligibility Rules3Vectors to Containers
Vectors, Lists, and Index ZeroTuples and Exact UnpackingNamed Lists and Dictionariesunique and Shallow CopiesRecap: Clean an Inventory6Reliable Python Programs
readLines and Text ContractsConditions and Cleanupsource and Module ImportsAnnotations and Runtime TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler