Skip to main content
Albero Academy

Inheritance

Build specialised classes on top of general ones and reuse behaviour.

Object-Oriented Programming11 min

Inheritance lets one class build on another, reusing its attributes and methods and adding or changing what it needs. It models "is-a" relationships: a Student is a Person, so it inherits everything a Person can do.

Subclassing & super()

A subclass lists its parent in parentheses. Call super() to reuse the parent's implementation:

subclassing
class Person:
def __init__(self, name):
self.name = name
def greet(self):
return f"Hi, I'm {self.name}"
class Student(Person): # Student inherits from Person
def __init__(self, name, track):
super().__init__(name) # run Person's constructor first
self.track = track # then add Student-specific state
def greet(self): # OVERRIDE the parent's method
return f"{super().greet()}, learning {self.track}"
Student("Aanya", "Python").greet() # "Hi, I'm Aanya, learning Python"

Overriding & extending

A subclass can override a method (replace it entirely) or extend it (call super() then add to it, as above). Methods it doesn't override are inherited unchanged.

Prefer shallow hierarchies

Key takeaways

  1. 01Inheritance models "is-a": a subclass reuses a parent's attributes and methods.
  2. 02List the parent in parentheses: class Student(Person).
  3. 03super() calls the parent implementation (e.g. its __init__).
  4. 04A subclass can override a method or extend it via super().
  5. 05Keep hierarchies shallow; favour composition for "has-a" relationships.

Finished this chapter?

Mark it complete to track your progress through Python.