Create Subclass From Superclass in Python

In Python, you can get the characteristics you want from an existing super class (parent) to create a new sub class (child). This Python feature is called inheritance.

By inheritance, you can

  • prevail over the features of a parent or super class.
  • change the features that you think are important.
  • add new properties to your child or sub class or derived class.

Every object-oriented programming language is precious if it supports inheritance. Python not only supports inheritance but also assists multiple inheritances as well. If we say inheritance is the process of deriving new classes from existing ones. By doing this, we get a hierarchy of classes. In most class-based object-oriented languages, an object created through inheritance (a subclass or child object) contains all the necessary information. However, there are exceptions in some programming languages, as all child classes get the properties and behaviors of the parent object (superclass).

In this article, we are learning to develop a child object sub class from a parent object super class known as inheritance. Super classes are sometimes called ancestors as well. There exists a hierarchical relationship between classes.

Inheritance allows you to create classes built upon existing classes, and the sub class built through this method enables you to inherit the features and methods of the super class. This means that this method supports code reusability. Generally, the procedures or software inherited by a sub class are considered to be reused in the subclass. The relationships of objects or classes through inheritance give rise to a directed graph.

If we have several similar classes, we can define the common functionalities in one class and define child classes of this parent class and implement specific functionalities there. Using here super(), a Python Built-in function is a slightly better procedure of calling the parent class for initialization. Following code is the best example of super class and sub class relationship.

Create Sub Class From Super Class Using the super() Function

In this code block, we will first create a super class Animal which has some name, and it prints the color of Animal. Then we will create the sub class Cat type of the Animal class, and we will pass the Cat class object using the super() method to the parent super class, and it will print the color concerning the cat name.

class Animal(object):
  def __init__(self, animalName):
    print(animalName, 'color is white.')

class Cat(Animal):
  def __init__(self):
    print('Cat Name is Milo.')
catobject = Cat()


Cat Name is Milo.
Milo color is white.
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python Class

  • Call a Class in Python
  • Create an Abstract Class in Python