Clear, practical technology insights BSOD Code Lookup · Windows Error Code Lookup · Wi-Fi Troubleshooting · PC Troubleshooting Checklist

Python Class Inheritance: Subclasses, Overrides, and super()

Build a Python subclass, add an attribute, override a method, and see how super() and isinstance() behave in a complete example.

Table of Contents

In Python, a class inherits from another class by naming it in parentheses: class Bear(Animal):. A Bear can use methods defined by Animal, override methods it needs to specialize, and define methods and instance attributes of its own.

Class inheritance in Python (P1) Picture 1

Extend a class and initialize its attributes

class Animal:
    def __init__(self, name):
        self.name = name

    def describe(self):
        return self.name

    def eat(self):
        return f'{self.name} is eating'


class Bear(Animal):
    def __init__(self, name, fur_color):
        super().__init__(name)
        self.fur_color = fur_color

    def describe(self):
        return f'{super().describe()} has {self.fur_color} fur'

    def swim(self):
        return f'{self.name} is swimming'


polar_bear = Bear('Nora', 'white')
print(polar_bear.describe())  # Nora has white fur
print(polar_bear.eat())       # Nora is eating
print(polar_bear.swim())      # Nora is swimming

eat() comes from Animal, describe() is overridden, and swim() is new. Because Bear defines its own initializer, it calls super().__init__(name) to run the next initializer in the method resolution order. In this example, that initializer is Animal.__init__. It sets the instance’s name before Bear adds fur_color.

Check the relationship between the classes

assert isinstance(polar_bear, Bear)
assert isinstance(polar_bear, Animal)
assert issubclass(Bear, Animal)
assert Bear.__bases__ == (Animal,)

__bases__ lists direct base classes. Bear.__mro__ shows the full lookup order in this example: Bear, Animal, object. Use inheritance when the subclass can still honor the base class’s expected behavior. If you only need an object to use another object’s service, storing it as an attribute may be simpler.

See the Python tutorial on classes or practice with classes and testing in Python Fundamentals.

Discussion

Reader Comments 0

Sign in with email or Google to join the discussion.