Skip to content

Inheritance

Inheritance is a fundamental pillar of object-oriented programming. It allows you to create new classes based on existing classes, reusing and extending their functionality. This way, you can model “is a” relationships (for example, a Dog is an Animal).


  • Code reuse: Avoid repeating common attributes and methods.
  • Organization: Allows structuring logical hierarchies between classes.
  • Extension: You can add or modify behaviors in subclasses.

To create a class that inherits from another, simply indicate the base class in parentheses:

class BaseClass:
# attributes and methods
class SubClass(BaseClass):
# new attributes and methods

Suppose you have an Animal class and you want to create a Dog class that inherits from it:

Basic inheritance
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print('Makes a sound')
class Dog(Animal):
def speak(self):
print(f'{self.name} says: Woof!')
my_dog = Dog('Rex')
my_dog.speak() # Rex says: Woof!

In this example, Dog inherits the name attribute and the speak method from Animal, but redefines it to customize the behavior.


You can call methods of the base class using super(). This is useful for extending functionality without completely replacing it.

Using super()
class Animal:
def __init__(self, name):
self.name = name
def describe(self):
print(f'I am an animal called {self.name}')
class Cat(Animal):
def describe(self):
super().describe()
print('And I am a cat.')
g = Cat('Michi')
g.describe()

Output:

I am an animal called Michi
And I am a cat.

In Python, a class can inherit from multiple classes at the same time:

class ClassA:
pass
class ClassB:
pass
class SubClass(ClassA, ClassB):
pass

  • Inheritance allows you to create classes that reuse and extend others.
  • Use super() to access methods of the base class.
  • You can redefine methods to customize the behavior in subclasses.
  • Python allows multiple inheritance.

Ready to practice? Try creating a base class Vehicle and a subclass Car that adds its own method.