Inheritance and Overriding Behaviour
A subclass reuses a superclass's methods and can extend its initialization or replace methods. Instance fields still need initialization. Shared behaviour is written once, with each difference in the class responsible for it.
What a learner can do afterwards
- Write a subclass that adds one field and overrides one method
- Predict which version of a method runs for an object of the subclass
- Say when two classes should share a parent and when they should not
1 · Read
class Child(Parent) makes Child a subclass of superclass Parent, with inherited methods. Instance fields need initialization. Replacing __init__ does not automatically call the parent's initializer. ```python class Vehicle: def __init__(self): self.wheels = 4 def refuel(self): return "fuel added" def trip_info(self): return "vehicle" ```
Overriding defines a subclass version of an inherited method. It does not delete the parent's version. ```python class Shuttle(Vehicle): def trip_info(self): return "shuttle" ``` Calling trip_info on a Shuttle uses this version; calling it on a Vehicle uses Vehicle's version.
super() returns a proxy for inherited lookup. It does not run trip_info by itself. In these examples, super().trip_info() selects and calls Vehicle's version. An override can use its returned text, then add seats information. Calling self.trip_info() inside that same override calls the override again.
This subclass initializes the parent fields, adds an instance field and overrides trip_info. str converts the seat count to text. ```python class Bus(Vehicle): def __init__(self, seats): super().__init__() self.seats = seats def trip_info(self): return super().trip_info() + ": " + str(self.seats)
bus = Bus(12) ```
Every subclass must honour its parent's behavioural contract. PersistentStore.save(data) might promise that the saved data can be loaded after the process ends. A memory-only cache cannot meet that promise. Reusing a formatting method alone does not make it a valid PersistentStore child.
Sibling classes need not be kinds of one another; each must fit their common parent. Document includes read-only documents. Put replace_text(), promising a content change, on EditableDocument. Returning success without changing content breaks that promise. Polymorphism means different objects can respond to one method name.
Initialize required fields, look up each method separately, and call inherited methods through super().method(). Every child must honour its parent's contract.
Inheritance teaching adapted from the Introduction to Python Programming chapter 13 summary, with independently written Python examples, contract explanations and assessment repairs.
The rewritten inheritance reading was written for this dataset.
2 · Watch
به انگلیسیTake it off screen
Where it sits
8 questions wait behind this lesson, each with its answer explained. Every answer feeds the sky: stars light as they are learned, and dim when it is time to come back.