Skip to content

Basic Inheritance & Hierarchy

Inheritance is a fundamental pillar of Object-Oriented Programming that allows you to create new classes based on existing ones. It facilitates code reuse by allowing a Subclass (Child) to inherit the attributes and behaviors of a Base Class (Parent).

In Python, inheritance is not just about copying code; it’s about establishing a logical hierarchy where specialized objects can leverage and extend the functionality of more general ones.


Inheritance should only be used when there is a clear “is-a” relationship between the two entities.

  • A Manager is a Employee.
  • A Circle is a Shape.
  • A Smartphone is a Device.
syntax.py
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def get_details(self):
return f"{self.name} earns ${self.salary}"
# Manager inherits from Employee
class Manager(Employee):
def plan_meeting(self):
print(f"{self.name} is planning a meeting.")
m = Manager("Alice", 90000)
print(m.get_details()) # Inherited from Employee

Often, you don’t want to completely replace a parent’s method; you want to run the parent’s logic and then add your own. The super() function allows you to call methods from the parent class without explicitly naming it.

super_usage.py
class Manager(Employee):
def __init__(self, name, salary, department):
# Let the parent class handle name and salary
super().__init__(name, salary)
# Add the manager-specific attribute
self.department = department
def get_details(self):
# Call the parent's version and append more info
basic_info = super().get_details()
return f"{basic_info} and manages {self.department}"

3. Introspection: isinstance and issubclass

Section titled “3. Introspection: isinstance and issubclass”

Because of inheritance, an object can be an instance of multiple classes.

m = Manager("Alice", 90000, "HR")
print(isinstance(m, Manager)) # True
print(isinstance(m, Employee)) # True (Because Manager is an Employee)
print(isinstance(m, object)) # True (Everything is an object in Python)
print(issubclass(Manager, Employee)) # True

4. Under the Hood: The __bases__ Attribute

Section titled “4. Under the Hood: The __bases__ Attribute”

How does Python know which class is the parent? Every class has a hidden attribute called __bases__ that stores a tuple of its parent classes.

print(Manager.__bases__)
# Output: (<class '__main__.Employee'>,)

When you call a method like m.get_details(), Python first looks in the Manager class. If it’s not there, it checks the classes listed in __bases__.


TermMeaning
Base ClassThe parent class being inherited from.
SubclassThe child class that is inheriting.
OverridingReplacing a parent’s method with a child’s version.
ExtendingUsing super() to build upon a parent’s method.
ObjectThe root of all classes in Python 3.