Python Inheritance · Examples
Object-Oriented Python

Python Inheritance Examples

Short, runnable programs that show python inheritance in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the Python Inheritance lesson.

1Extend a parent method with super()

The child's label() reuses the parent's text and adds the sale price, so the shared formatting lives in one place.

Extend a parent method with super()
class Product:
    def __init__(self, name, price):
        self.name = name
        self.price = price

    def label(self):
        return f"{self.name}: ${self.price:.2f}"

class SaleProduct(Product):
    def __init__(self, name, price, discount):
        super().__init__(name, price)
        self.discount = discount

    def label(self):
        sale_price = self.price * (1 - self.discount)
        return super().label() + f" -> now ${sale_price:.2f}"

print(Product("Lamp", 40).label())
print(SaleProduct("Chair", 80, 0.25).label())
Expected outputLamp: $40.00
Chair: $80.00 -> now $60.00

2isinstance(), issubclass() and the lookup order

Inheritance can go several levels deep. __mro__ (method resolution order) lists the classes Python searches, in order, when you call a method.

isinstance(), issubclass() and the lookup order
class Animal:
    pass

class Bird(Animal):
    pass

class Penguin(Bird):
    pass

pingu = Penguin()
print(isinstance(pingu, Bird), isinstance(pingu, Animal))
print(isinstance(Animal(), Bird))
print(issubclass(Penguin, Animal))
print([cls.__name__ for cls in Penguin.__mro__])
Expected outputTrue True
False
True
['Penguin', 'Bird', 'Animal', 'object']

3Encapsulation with a leading underscore

_temp is marked as internal. Code outside the class is expected to go through set_temp(), which checks the value first.

Encapsulation with a leading underscore
class Thermostat:
    def __init__(self, temp):
        self._temp = temp

    def set_temp(self, value):
        if 10 <= value <= 30:
            self._temp = value
        else:
            print(f"{value} is out of range, keeping {self._temp}")

    def get_temp(self):
        return self._temp

home = Thermostat(21)
home.set_temp(45)
home.set_temp(24)
print("Now:", home.get_temp())
Expected output45 is out of range, keeping 21
Now: 24

4Custom exceptions are inheritance too

Your own error types inherit from Exception. Because of inheritance, except Exception would also catch them, and isinstance confirms the relationship.

Custom exceptions are inheritance too
class OutOfStockError(Exception):
    pass

def buy(stock, item):
    if stock.get(item, 0) == 0:
        raise OutOfStockError(f"{item} is sold out")
    stock[item] -= 1

stock = {"tea": 1}
for attempt in range(2):
    try:
        buy(stock, "tea")
        print("Bought tea")
    except OutOfStockError as err:
        print("Sorry:", err, "|", isinstance(err, Exception))
Expected outputBought tea
Sorry: tea is sold out | True

Practise next

Python Inheritance exercises → Back to the lesson

Python Polymorphism and Duck Typing examplesPython Multiple Inheritance and MRO examplesPython Composition: Has-A vs Is-A examples