Inheritance and Method Lookup
Lesson 39 of 48 in Coddy's Python for C++ Developers course.
C++ needs virtual for runtime overriding through a base reference in this example; override asks the compiler to check the match. Python ordinary methods are looked up on the runtime object without a virtual declaration. super() delegates along the method resolution order, not necessarily to one hard-coded parent in multiple inheritance. If a subclass defines __init__, explicitly call super().__init__ when base initialization is required.
C++17 excerpt: inside main
Standard-library headers are supplied in the runnable companion program.
struct Base {
virtual std::string label() const { return "base"; }
virtual ~Base() = default;
};
struct Child : Base {
std::string label() const override { return Base::label() + "!"; }
};
Child child;
Base& base = child;
std::cout << base.label() << '\n';Python
class Base:
def label(self):
return "base"
class Child(Base):
def label(self):
return super().label() + "!"
print(Child().label())Porting trap
Python assignment to a base-typed annotated name does not slice the object. C++ copying Child into a Base value can slice away derived state and behavior; use a reference or pointer for polymorphic C++ access.
Implement the task below in its editable Python modules. The locked driver.py supplies execution and checks. Keep the specified imports and 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 C++ Developers
1From C++ to Python
Run Your First Python ProgramStreams to printNames, auto, and constDivision and Integer RangeBlocks and Name ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Range Loops and RebindingEntries and enumerateLoop Control Without ++Algorithms and ComprehensionsRecap: Build a Ranking2Values and Decisions
None, nullptr, and boolValues, Addresses, IdentityTruth Tests and OperandsBranches and Value SelectionRecap: Eligibility Rules5Functions, Calls, and Closures
Functions and Shared ObjectsDefaults and Named ArgumentsPacking and Unpacking CallsClosures and Capture TimingRecap: Refactor a Pricing Tool8Composition and Dispatch
Composition Without Value CopyInheritance and Method LookupVirtual Calls and Duck TypingEquality Beyond operator==Recap: Notification Channels3STL Habits and Python Objects
From vector to listTuples and Structured BindingsMaps, Keys, and OrderingValue Copies and Shared ListsRecap: Clean an Inventory6Errors, Resources, and Modules
Text Input and Exact OutputExceptions and RAIIModules Instead of HeadersHints Are Not Static TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler