Python: Class Inheritance and Compositions


A Derived class inherits from a Base class and is a specialized version of Base. It allows defining a class that inherits all the methods and properties of another class.

The syntax for a subclass definition looks like this:

class DerivedClassName(BaseClassName):

Super() function will make the child class inherit all the methods and properties from its parent:


import json

class Pet:
    def __init__(self, name): = name

class Dog(Pet):
    def __init__ (self, name, breed=None):
        self.breed = breed

    def say_hi(self):
        return f"Hi {}"

class ExportJson:
    def to_json(self):
        return json.dumps({
            "breed": self.breed

class ExDog(Dog, ExportJson):

Pet is a Base Class, Dog – is a subclass of Pet Class, ExDog – a subclass of multiple classes: Dog and ExportJson.

Each class is a subclass of class “object”. To check the subclass of the class: issubclass

Check an instance of the class: isinstance

Method Resolution Order – the order of the classes Python is looking for attributes or method: __mro__


If we have another class that needs to be added, we will have to extend the ExDog class each time. It’s better to pass it as the attribute:

class Pet – name
class Dog – breed
class ExDog – exporter
as a result: instance dog will have a name (from Pet), a breed (from Dog) and exporter function passed to the ExDog class (None as default, but using ExportJson if export() method is used)