Inheritance Beyond Traits
Lesson 39 of 48 in Coddy's Python for Rust Developers course.
Rust has traits and composition but no class inheritance that reuses stored fields from a parent class. Python supports subclassing and method overriding. super() follows the method resolution order and delegates to the next applicable implementation; it is not an object copy. In a simple single-inheritance example this reaches the base method. A Rust wrapper that holds a base value can provide similar output through explicit delegation, but that is composition rather than inheritance.
Rust excerpt inside main
struct Base;
impl Base { fn label(&self) -> String { String::from("base") } }
struct Child { base: Base }
impl Child { fn label(&self) -> String { self.base.label() + "!" } }
println!("{}", Child { base: Base }.label());Python
class Base:
def label(self):
return "base"
class Child(Base):
def label(self):
return super().label() + "!"
print(Child().label())Porting trap
Rust trait default methods and Python super calls are not identical mechanisms. In multiple inheritance, super follows the computed order, not merely a hard-coded parent.
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 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 Ranking2Values and Decisions
Option and NoneEquality and Object IdentityTruth Tests and FallbacksIf Expressions and elifRecap: Eligibility Rules5Functions and Closures
Functions and Shared ObjectsNamed Arguments and DefaultsPacking Calls and OptionsClosures and Capture TimingRecap: Refactor a Pricing Tool8Composition and Dispatch
Composition and AliasesInheritance Beyond TraitsTraits and Duck TypingDerived Equality and DataclassRecap: Notification Channels3Ownership 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