Inheritance and super
Lesson 39 of 48 in Coddy's Python for Swift Developers course.
Swift classes can inherit and explicitly mark overrides; structs cannot inherit class storage. Python classes can inherit and override methods without an override keyword. super delegates according to the method resolution order. In a single-base example this reaches the base implementation, while multiple inheritance makes the ordering more important. Use composition when you only want to delegate work to a dependency, rather than claiming a subtype relationship.
Swift example
class Base { func label() -> String { "base" } }
class Child: Base {
override func label() -> String { super.label() + "!" }
}
print(Child().label())Python
class Base:
def label(self):
return "base"
class Child(Base):
def label(self):
return super().label() + "!"
print(Child().label())Porting trap
Python super is not a copied base object and is not always a hard-coded direct-parent call in multiple inheritance.
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 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 Swift Developers
1From Swift to Python
Run Your First Python ProgramPrinting and Stringslet, var, and RebindingInt Range and DivisionIndentation and Block ScopeRecap: Rewrite a Receipt4Iteration and Transformations
for and Half-Open Rangesenumerated to enumeratewhile and Loop Controlmap, filter, ComprehensionsRecap: Build a Ranking2Values and Decisions
Optionals and NoneEquatable and IdentityBool Conditions and FallbacksBranches and TernariesRecap: Eligibility Rules5Functions and Closures
Functions and Explicit ReturnArgument Labels and DefaultsVariadics and Call ExpansionCapture Lists and DefaultsRecap: Refactor a Pricing Tool8Composition and Dispatch
Composition and Value CopiesInheritance and superProtocols and Duck TypingEquatable to DataclassRecap: Notification Channels3Value Types to Shared Objects
Array to listTuples and UnpackingDictionary Lookup and OrderValue Copies and AliasesRecap: Clean an Inventory6Errors and Modules
Input and String Formattingthrows, defer, and withModules and Main GuardsHints and Runtime TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler