Inheritance and Initialization
Lesson 39 of 48 in Coddy's Python for Java Developers course.
Name a base class in parentheses and override methods by defining them on the subclass. In this single-inheritance example, super().label() reuses the inherited behavior. More generally super follows Python's method resolution order; it is not an ordinary stored parent object. If a subclass defines __init__, call super().__init__(...) explicitly when base initialization is needed. If it defines no initializer, the inherited initializer can be used. Java constructor chaining follows different rules, including implicit super() where applicable.
Java excerpt: class member declarations
// Class members
static class Base { String label() { return "base"; } }
static class Child extends Base {
@Override String label() { return super.label() + "!"; }
}Python
class Base:
def label(self):
return "base"
class Child(Base):
def label(self):
return super().label() + "!"
print(Child().label())Watch the difference
Python does not require Java @Override to dispatch an override. A misspelled method name creates a different method rather than a checked override. Read current instance state instead of caching a base cost that may later change.
Practice
Apply this comparison in the task below. Editable files: pass_model.py, discount_pass.py. Keep the provided imports and the required API names. The locked driver.py supplies execution and checks; do not edit it.
Challenge
BeginnerImplement Pass(label,price), storing attributes and returning current price from cost(). Implement DiscountPass(label,price,discount) as a subclass, initialize the base via super().__init__, and return max(0, base cost minus discount) from its override. Inputs are label and nonnegative price/discount. The driver prints regular and discounted label/cost pairs, changes the discounted price by 10, then prints its new cost; it also checks subclassing. Unlike Java implicit constructor chaining, Python base initialization needs the explicit call here.
Editable files: pass_model.py, discount_pass.py. Keep the provided imports and the required API names. The locked driver.py supplies execution and checks; do not edit it.
Implement the named definitions in the editable modules without input or printing. The driver owns input/output and may call the APIs again on fresh data without producing extra output.
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 Java Developers
1From Java Classes to Python
Run Python Without a ClassPrinting Text and CommentsBindings, Types, and finalDivision and Numeric TypesIndentation Defines BlocksRecap: A Python Receipt4Iteration and Transformations
Enhanced Loops and rangeIndexes and Map EntriesSentinels and Loop ControlFrom Streams to ComprehensionsRecap: Stable Ranking2Values Beyond Java Primitives
None and Boolean ValuesValue Equality and IdentityTruth Tests Beyond booleanBranches and Value SelectionRecap: Missing or Eligible5Functions Beyond Methods
Functions Outside ClassesDefaults Instead of OverloadsVarargs and Keyword OptionsScope and Callable ObjectsRecap: Pricing Functions8Behavior Beyond Interfaces
Collaborators Without CastsInheritance and InitializationInterfaces and Duck TypingRecords and Data ClassesRecap: Pluggable Channels3Collections and Object Sharing
Lists and ArrayList HabitsTuples Without Record ClassesDictionaries and Java MapsShared References and CopiesRecap: Inventory Collections6Contracts, Errors, and Modules
Text Input and Exact OutputValueError and TypeErrorModules Versus Utility ClassesAnnotations Are Not Java TypesRecap: Validate a Batch9Project: An Order Processor
Project: Model an OrderProject: Pricing PoliciesPractice on your own: Online Python compiler