Overrides and super
Lesson 39 of 48 in Coddy's Python for C# Developers course.
Extend inherited behavior while initializing base state correctly.
C# reference excerpt
Executable statements use C# top-level program style; type-only examples are declarations. System names assume the usual using System directive.
class Pass {
public int Price;
public Pass(int price) { Price = price; }
public virtual int Cost() => Price;
}
class SalePass : Pass {
public SalePass(int price) : base(price) { }
public override int Cost() => Math.Max(0, base.Cost() - 2);
}Python
class Pass:
def __init__(self, price):
self.price = price
def cost(self):
return self.price
class SalePass(Pass):
def __init__(self, price):
super().__init__(price)
def cost(self):
return max(0, super().cost() - 2)What changes
C# marks overridable methods virtual and implementations override. Python overrides by defining the same method name in the subclass. If a subclass defines __init__, call super().__init__ explicitly when base initialization is needed. In this single-inheritance example, super locates the base implementation; more generally it follows method resolution order, not a hard-coded parent name.
Transfer mistake
Overriding cost should use current state, not a price captured during construction. Do not write super.cost(): super() returns the proxy used for method lookup.
Your task
Implement Pass(label, price) storing both fields and cost() returning price. In its own file implement DiscountPass(label, price, discount) inheriting Pass, initializing base state through super().__init__, and storing discount. Override cost to subtract discount from the current base cost and clamp at zero. The driver reads label, nonnegative price, and nonnegative discount. It prints label/cost for regular and discounted instances, adds 10 to the discounted price, and prints its recalculated cost. A silent check verifies inheritance.
Challenge
BeginnerImplement Pass(label, price) storing both fields and cost() returning price. In its own file implement DiscountPass(label, price, discount) inheriting Pass, initializing base state through super().__init__, and storing discount. Override cost to subtract discount from the current base cost and clamp at zero. The driver reads label, nonnegative price, and nonnegative discount. It prints label/cost for regular and discounted instances, adds 10 to the discounted price, and prints its recalculated cost. A silent check verifies inheritance.
Editable implementation files: pass_model.py, discount_pass.py. The locked driver.py is the supplied launcher or input/output harness and must remain unchanged.
Keep the supplied imports and exact API names. Return results or raise the required exceptions; do not read input or print from these implementation 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 C# Developers
1C# Foundations in Python
Run the Python WorkspaceOutput, Strings, and CommentsTyped Locals to Python NamesDivision and RemaindersIndentation Instead of BracesRecap: Port a Receipt4Loops and Transformations
From foreach to forIndexes and Dictionary ItemsSentinels and Loop ControlFrom LINQ to ComprehensionsRecap: Stable Ranking2None and Decisions
Nullable Values and NoneEquality, Identity, and TypesTruth Tests and FallbacksBranch PriorityRecap: Eligibility Rules5Functions and Scope
Define Functions and ReturnNamed Arguments and DefaultsStar Arguments and UnpackingCallbacks and Python ScopeRecap: Pricing Functions8Composition and Inheritance
Replaceable CollaboratorsOverrides and superInterfaces and Duck TypingRecords and Value EqualityRecap: Dispatch by Behavior3Collections and References
From List<T> to listTuples and UnpackingDictionary Keys and ValuesSets, Aliases, and CopiesRecap: Stock Lookup6Reliable Python Programs
Input and Exact OutputExceptions and ValidationImports and the Main GuardType Hints and Runtime TypesRecap: Validate a Batch9Project: Order Processor
Project 1: Order ModelProject 2: Pricing PoliciesPractice on your own: Online Python compiler