43
Inheritance
Inheritance: Extending Capabilities on Top of Existing Classes
What might confuse you right now
"Can't I just copy the parent class code?"
Sure, it'll run. But duplicate code is a maintenance nightmare. Inheritance exists to reuse shared capabilities and extend the differences.
One-line definition
Inheritance lets a child class reuse parent attributes/methods, and override or add new behavior.
Real-life analogy
A parent class is like a generic job description. A child class is a specific role that adds extra responsibilities on top.
Minimal runnable example
class Animal:
def speak(self):
return "..."
class Dog(Animal):
def speak(self):
return "Woof"
print(Dog().speak())
Quick quiz (5 min)
- Write a
Vehicleparent class andCar/Bikechild classes. - Override the
run()method. - Compare polymorphic call results.
Quiz answer guidelines & grading criteria
- Answer direction: working code that covers core conditions and edge inputs from the prompt.
- Criterion 1 (Correctness): Main flow produces correct results, key branches execute.
- Criterion 2 (Readability): Clear variable names, no excessive nesting.
- Criterion 3 (Robustness): Basic protection against null values, type errors, or unexpected input.
Transfer task (homework)
Model a "generic notification + email notification / SMS notification" scenario using inheritance.
Acceptance criteria
You can independently:
- Write a basic inheritance structure
- Override methods correctly
- Avoid unnecessary code duplication
Common errors & debugging steps (beginner edition)
- Can't understand the error: read the last line for the error type (e.g.,
TypeError,NameError), then trace back to the relevant code line. - Not sure about a variable's value: temporarily add
print(variable, type(variable))at key points to verify data matches expectations. - Code changes aren't taking effect: confirm the file is saved, you're running the right file, and your terminal environment (venv) is correct.
Common misconceptions
- Misconception: Deeper inheritance hierarchies are more professional.
- Reality: Deep hierarchies increase complexity. Prefer simple structures.