▶ Sign up free for the video, slides & prompts
The lesson below is open to all. Enter your email once to unlock every video, slide deck, prompt and code example on this device.
Checking…
Inheritance
Build new classes from existing ones, and when not to.
🎬 Video version coming soon — read it now
Inheritance lets a new class reuse an existing class and add or change parts of it. The new class is the child (subclass); the original is the parent (base class).
What happened
class Manager(Employee)means a Manager is an Employee. It getsdescribeand everything else for free.super().__init__(...)runs the parent's constructor sonameandsalaryare set up properly.- Manager overrides
annual_paywith its own version, which still uses the parent's viasuper(). - The loop calls
describe()on each person without checking their type, and each one computes its pay correctly. That's called polymorphism: same method name, behaviour suited to each class.
isinstance
When NOT to inherit
Use inheritance only for a genuine "is a" relationship. A Manager is an Employee. But a Car is not an Engine; a car has an engine. For "has a", store one object inside another (composition):
Deep inheritance chains (A → B → C → D → E) become hard to follow. Most good Python code uses shallow inheritance, one or two levels, and lots of composition.
In one line
A child class inherits a parent's attributes and methods, can override them and call the parent with super(); use it only for real "is a" relationships.
Share with a friend