Open Classes and super
Lesson 39 of 48 in Coddy's Python for Kotlin Developers course.
Kotlin classes and methods are final by default and need open or an interface contract for overriding. Python ordinary classes and methods are overridable without open or override keywords. Python super continues method lookup according to the method resolution order. If a Python subclass defines __init__, it must call inherited initialization when that state is required.
Kotlin
open class BaseLabel { open fun text() = "base" }
class LoudLabel : BaseLabel() { override fun text() = super.text() + "!" }
fun main() { println(LoudLabel().text()) }Python
class BaseLabel:
def text(self):
return "base"
class LoudLabel(BaseLabel):
def text(self):
return super().text() + "!"
print(LoudLabel().text())Porting trap
Do not add Kotlin override syntax to Python. A misspelled Python method name silently defines a different method unless a test or tool catches it.
Complete the task in its editable modules. The locked driver.py supplies execution; keep the required API names.
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 Kotlin Developers
1From Kotlin to Python
Run Your First Python ProgramPrint and String TemplatesVal, Var, and Python NamesDivision and Integer WidthSuites and Block ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Ranges and Loop BindingsEntries and withIndexUpdates and Loop ControlCollection PipelinesRecap: Build a Ranking2Values and Decisions
Nullable Types and NoneEquality and IdentityBoolean Conditions and orIf Expressions and ElifRecap: Eligibility Rules5Functions and Closures
Functions and Shared ListsDefaults and Named CallsVararg and Keyword PackingClosures and Lambda ResultsRecap: Refactor a Pricing Tool8Composition and Dispatch
Injected CollaboratorsOpen Classes and superInterfaces and BehaviorData Classes and EqualityRecap: Notification Channels3Collections and Shared State
Read-only Lists and MutationPair and Tuple UnpackingMap Lookup and Missing KeysShallow Copies and SetsRecap: Clean an Inventory6Input, Errors, and Modules
Console Input and FormattingExceptions and Resource ScopeImports and Entry PointsStatic Types and AnnotationsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler