NextMethod and super
Lesson 39 of 48 in Coddy's Python for R Developers course.
R S3 dispatch can follow a class vector, and NextMethod continues generic dispatch to another applicable method. Python classes declare bases and use a method resolution order. Python super() constructs a proxy for continuing lookup after the current class; call a method on that proxy and pass its required arguments. This is not an R class-vector edit or a direct substitute for every NextMethod use. In a single-base constructor, super().__init__ initializes the inherited portion before the subclass adds its fields. An overridden method does not automatically run its parent implementation unless you explicitly delegate.
R
label <- function(x) UseMethod("label")
label.child <- function(x) paste0(NextMethod(), "?")
label.base <- function(x) paste0(x$text, "!")
x <- structure(list(text="go"), class=c("child", "base"))
cat(label(x), "\n", sep="")Python
class Base:
def label(self, text):
return text + '!'
class Child(Base):
def label(self, text):
return super().label(text) + '?'
print(Child().label('go'))Porting trap
Calling Python super() alone does not invoke a parent method. Name the method on the proxy.
Challenge
BeginnerImplement Pass(label, price) with stored attributes and cost() returning the integer price. Implement subclass DiscountPass(label, price, discount), initializing base state through super().__init__ and storing discount. Override cost() to return the base cost minus the discount, clamped at zero. Input is label, nonnegative price, and nonnegative discount on separate lines. The driver prints the label and cost for a regular pass and a discounted pass, then increases the discounted pass's price by 10 and prints its new cost. Calculate from current state.
The locked driver handles input and output. Submit only the required class and function definitions with the exact API names. Do not read input or print from your classes.
The locked driver also verifies the required subclass relationship at runtime.
Your code goes in the editable files pass_model.py and discount_pass.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 pass_model import Pass
from discount_pass import DiscountPass
assert issubclass(DiscountPass, Pass), "Required subclass relationship missing"
label = input()
price, discount = int(input()), int(input())
a, b = Pass(label, price), DiscountPass(label, price, discount)
print(a.label, a.cost())
print(b.label, b.cost())
b.price += 10
print(b.cost())
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 Ranking2Values and Decisions
NULL, NA, and NoneVector Equality and IdentityScalar Conditions, Not Vectorsifelse and Scalar SelectionRecap: Eligibility Rules5Functions and Environments
Explicit Function ReturnsLazy and Eager DefaultsDots Versus Star ArgumentsEnvironments and nonlocalRecap: Refactor a Pricing Tool8Composition and Dispatch
Store a CollaboratorNextMethod and superGenerics to Duck TypingRecords and Generated EqualityRecap: Notification Channels3Vectors 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