Python Inheritance
Python · Functions & OOP
Theory
Inheritance lets a new class (the child or subclass) reuse and extend an existing class (the parent or base class). Writing class Manager(Employee) means a Manager automatically has every attribute and method of Employee, and can add its own (team_size) or override a parent method by defining one with the same name.
super() gives access to the parent's version of a method. In Manager.__init__, super().__init__(name) lets Employee set self.name, then the child adds self.team_size. When you call a method on an object, Python searches the object's class first, then its parents in order (the method resolution order, visible via Manager.__mro__), and uses the first match it finds.
Why we use it
Inheritance avoids duplicating shared code. Common logic lives once in the parent, and each child adds only what is different, so a fix in the parent automatically reaches every subclass.
When to use it
Use inheritance for a true 'is-a' relationship (a Manager is an Employee). If one class merely uses another (a Car has an Engine), prefer composition - storing an object as an attribute - instead of deep inheritance chains.
How it works
- Call m.describe() on a Manager object
- Look for describe in class Manager
- Defined in Manager? Yes: Run the Manager version (override). No: Look in parent class Employee.
- Defined in Employee? Yes: Run the inherited version. No: Search up to object, else AttributeError.
- Method runs with self = m
Syntax
class Child(Parent):
...Example
class Manager(Employee):
def __init__(self, name, team_size):
super().__init__(name)
self.team_size = team_sizeKey points
- super() calls the parent class's methods
- Supports method overriding - same name in child replaces parent's
- isinstance(m, Employee) is True for a Manager
- Python supports multiple inheritance; the MRO decides lookup order
- Prefer composition when the relationship is 'has-a', not 'is-a'