Parent Calls and super
Lesson 39 of 48 in Coddy's Python for PHP Developers course.
PHP subclasses use extends and can call a parent implementation through parent::. Python lists base classes in parentheses and uses super() to continue method lookup. In single inheritance this often reaches the parent; in cooperative multiple inheritance it follows the method resolution order, so it is not simply a hard-coded parent name. An override can extend a result by calling the inherited implementation.
PHP 8.3
<?php
class BaseLabel { public function text() { return 'base'; } }
class LoudLabel extends BaseLabel {
public function text() { return parent::text() . '!'; }
}
echo (new LoudLabel())->text(), "\n";Python
class BaseLabel:
def text(self):
return "base"
class LoudLabel(BaseLabel):
def text(self):
return super().text() + "!"
print(LoudLabel().text())Porting trap
When a Python subclass defines __init__, inherited initialization is not automatically repeated. Call super().__init__(...) when that initialization is needed. Do not pass self to a bound super method.
Complete the task in the editable Python files. Keep the required function and class names; the locked driver.py supplies execution.
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 PHP Developers
1From PHP to Python
Run Your First Python ProgramEcho, Strings, and printVariables Without Dollar SignsDivision and Numeric TextIndentation and SuitesRecap: Rewrite a Receipt4Iteration and Transformations
Foreach and rangeKeys, Items, and enumerateWhile Without IncrementFilters and Sort KeysRecap: Build a Ranking2Values and Decisions
Null, None, and Missing KeysStrict Equality Is Not isThe Zero String TrapElif and Value SelectionRecap: Eligibility Rules5Functions and Closures
Functions and Mutable InputsNamed Calls and Default StateVariadics and Call UnpackingArrow Capture and Late BindingRecap: Refactor a Pricing Tool8Composition and Dispatch
Sharing CollaboratorsParent Calls and superInterfaces and Duck TypingEquality and DataclassesRecap: Notification Channels3Arrays and Python Collections
PHP Arrays and Python ListsDestructuring and TuplesKeys, Null, and getArray Copies and List AliasesRecap: Clean an Inventory6Input, Errors, and Modules
CLI Input and Exact OutputConversion Errors and CleanupImports Instead of requireType Hints Are Not PHP TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler