A class contains the sub-class. A class is considered a broader term and the subclass is derived from it. For example, an animal is a class; mammals, birds, and reptiles are the subclasses. Cats, dolphins, crows, sparrows, lizards, and snakes are further subclasses of these subclasses.

In this article, we will learn how to create a subclass from a superclass. Before diving into how we can make a subclass from a superclass, we will understand what is a subclass and why is it important.

What is the Python subclass?

In Python, a subclass is a class that is derived from another class ‘superclass’. The subclass gets all the properties and methods from the superclass. This phenomenon is known as ‘Inheritance’ in object-oriented programming where the child takes all the attributes from the parent.

Importance of Subclasses in Python

Now the question arises Why do we even make the subclasses? There are a few reasons why making the subclasses can be beneficial. The reasons are listed below

  • Subclasses make the code more structured and cleaner so that it is convenient to organize the code.
  • Subclasses remove any redundancy of the code as the same attributes are given to the subclass as the superclass
  • A subclass contains its own properties and methods too therefore extending the functionality while inheriting the functionality from the parent class

How to Create a Subclass in Python?

To create a subclass in Python, a class need to be defined with the superclass name in the brackets. The subclass gets all the properties of the superclass. Let’s learn how we can create a subclass in Python.

Example 1

The following code demonstrates how a subclass can be created in Python:

# superclass (parent class)
class CelestialBody():
    def display1(self):
        print("This is a celestial body")

# subclass (child class) for stars
class Star(CelestialBody):
    def display2(self):
        print("This is a star")

# subclass (child class) for planets
class Planet(CelestialBody):
    def display2(self):
        print("This is a planet")

# Creating objects of the subclasses
sun = Star()
mars = Planet()
# Calling the methods
sun.display1()
sun.display2()
mars.display1()
mars.display2()

In this code:

  • A superclass ‘CelestialBody’ is defined. The parent class contains the method ‘display1()’ which will print the message ‘This is a celestial body’ when called.
  • Next, the subclasses will be defined. In the above code, two subclasses ‘star’ and ‘planet’ are defined. Both the subclasses will inherit all the properties and methods from the superclass ‘CelestialBody’. This means the subclasses can call the ‘display1()’ method.
  • Each subclass has its own method ‘display2()’ to which only they have access. The display2() method for the ‘star class gives the output ‘This is a star’ while the ‘Planet’ class gives the output ‘This is a planet.
  • Then two objects will be created. ‘sun’ will be an instance of the ‘Star’ class while ‘mars’ will be an instance of the ‘Planet’ class.
  • These methods will be then called. ‘sun.display1()’ calls the ‘display1()’ method from the superclass because it inherits properties from the parent class as well as giving the output ‘This is a celestial body’. ‘sun.display2()’ calls the ‘display2()’ method from the ‘Star’ subclass printing ‘This is a star’. ‘mars.display1()’ calls the ‘display1()’ method from the superclass ‘Celestial Body’ printing ‘This is a celestial body.’ The ‘display2()’ method from the ‘Planet’ subclass will be called. Hence, ‘mars.display2()’ will print ‘This is a planet.

Output:

The child class gets all the properties and methods from the parent class but the parent class can not get the properties of its child class. If an instance of the parent class will call a certain method from the child class, it will throw an attribute error.

Example 2

This example uses the ‘__init__’ function which is equivalent to the C++ constructor when referring to object-oriented programming. The function is called whenever an object is created from a class. The __init__ method lets you call the properties of the object and is used inside the classes. 

Let’s look at another example of how we can create a subclass in Python using the __init__ function:

# superclass
class CelestialBody():
    def __init__(self, cb_name):
        self.name = cb_name

    def display1(self):
        print("In superclass method: This is a celestial body named", self.name)

# subclass for stars
class Star(CelestialBody):
    def __init__(self, star_name, star_temperature):
        super().__init__(star_name)
        self.temperature = star_temperature

# superclass
class CelestialBody():
    def __init__(self, cb_name):
        self.name = cb_name

    def display1(self):
        print("In superclass method: This is a celestial body named", self.name)

# subclass for stars
class Star(CelestialBody):
    def __init__(self, star_name, star_temperature):
        super().__init__(star_name)
        self.temperature = star_temperature

    def display2(self):
        print("In subclass method: This is a star named", self.name, "with a temperature of", self.temperature, "Kelvin.")

# subclass for planets
class Planet(CelestialBody):
    def __init__(self, planet_name, planet_type):
        super().__init__(planet_name)
        self.type = planet_type

    def display2(self):
        print("In subclass method: This is a planet named", self.name, "of type", self.type)

# Creating objects of the subclasses
sun = Star("Sun", 5778)
earth = Planet("Earth", "Terrestrial")

# Calling the methods
sun.display1()
sun.display2()

earth.display1()
earth.display2()

# Accessing attributes directly
print("Outside both methods: name of star:", sun.name, "temperature of star:", sun.temperature)
print("Outside both methods: name of planet:", earth.name, "type of planet:", earth.type)

In the above code,

  • The superclass ‘CelestialBody’ is defined with the ‘__int__’ method which takes the parameter ‘cb_name’ representing the celestial body’s name. The method initializes the ‘name’ attribute of the celestial body object that is given in the name.
  • The superclass contains the name ‘display1’ which gives the message that it is a celestial body along with the name of the celestial body (‘self.name’).
  • The ‘Star’ subclass will inherit the properties from the ‘CelestialBody’ superclass that uses the syntax ‘class Star(CelestialBody)’ meaning that the ‘Star’ subclass has all the properties of the ‘CelestialBody’ superclass.
  • The ‘__init__’ method of the ‘Star’ subclass takes the two parameters ‘star_name’ and ‘star_temperature’. The superclass method __int__ is called using ‘super().__init__(star_name)’. This sets the ‘name’ attribute which is inherited from the superclass. It also sets the ‘temperature’ which is the attribute only specified to the stars.
  • The subclass contains a second method names ‘display2’ that prints the message representing it as a star along with its temperature (‘self.temperature’) and its name (‘self.name’).
  • The ‘Planet’ subclass inherits from the ‘CelestialBody’ just like the ‘Star’ subclass.
  • The ‘__init__’ method of the ‘Planet’ subclass takes the two parameters ‘planet_name’ and the ‘planet_type’. It calls the ‘__init__’ method of the superclass using the ‘super().__init__(planet_name)’ to set the ‘name’ attribute inherited from the superclass. It also sets ‘type’ which is an attribute specified for planets only.
  • The subclass contains a method ‘display2’ that gives the message telling that it is a planet along with its name (‘self.name’) and type (‘self.type’).
  • The objects ‘sun’ and ‘earth’ are created from the ‘Star’ and ‘Planet’ subclasses accordingly.
  • The relevant information about the name and the attributes are passed to the constructors.
  • display1()’ and ‘display2()’ are called on these objects to get the output messages specified to each subclass
  • The attributes ‘name’ and ‘temperature’ can be accessed directly from the ‘sun’ object that is an instance of the ‘Star’ subclass and the attributes ‘name’ and ‘type’ are directly taken from the ‘earth’ object which is an instance of the ‘Planet’ subclass to get the final output

Output:

The output of the above code is:

Python super() Function

The super() function is a parent function whose attributes and methods are transferred to its child function which is a subclass. The return value for the super function is the parent() object. super() function enables multiple inheritances. The syntax for the super function is:

super()

super() function can be used instead to call the constructor and methods of the base class inside the derived class. The super() function returns the base class object and can be utilized to get the attributes of the child class.

Let’s see the following code for the demonstration of the super() function:’

# superclass
class CelestialBody():
    def __init__(self, cb_name):
        self.name = cb_name

    def display1(self):
        print("In superclass method: This is a celestial body named", self.name)

# subclass for moons
class Moon(CelestialBody):
    def __init__(self, moon_name, moon_distance):
        super().__init__(moon_name)
        self.distance = moon_distance

    def display2(self):
        print("In subclass method: This is a moon named", self.name, "at a distance of", self.distance, "kilometers.")

# Creating objects of the subclass
moon = Moon("Moon", 384400)

# Calling the methods
moon.display1()
moon.display2()

# Accessing attributes directly
print("Outside both methods: name of moon:", moon.name, "distance of moon:", moon.distance)

In the given code,

  • A new subclass ‘Moon’ is created which inherits from the superclass ‘CelestialBody
  • The ‘Moon’ subclass contains’ the attribute ‘distance’ which tells about the distance from its parent ‘CelestialBody’ class.
  • The ‘__init__’ method of the ‘Moon’ subclass uses the ‘super().__init__(moon_name)’ to call the constructor of the superclass ‘CelestialBody’. 
  • Moon_name’ is passed to initialize the ‘name’ attribute derived from the superclass
  • An object ‘moon’ is created from the ‘Moon’ subclass, and the information about the name and distance is passed to the constructor 
  • The superclass contains the method ‘display1()’ while the subclass contains the method ‘display2()’.
  • The super() function makes sure that the ‘name’ attribute gets initialized rightfully with the help of the superclass’s constructor 
  • Calling ‘moon.display1()’ prints ‘This is a celestial body named Moon’ while ‘moon.display2()’ gives ‘This is a moon named Moon at a distance of 384400 kilometers’.
  • The attributes name and distance can be directly accessed using ‘moon.name’ and ‘moon.distance
  • The output displays the message specific to the ‘Moon’ subclass

Output

The output of the above code is:

Conclusion

In this article, we learned about how we can make the subclass from a superclass, the __init__ function, and how we can use the super() function. Python subclasses play a key role in code organization and its reusability through inheritance. With the help of subclasses, we can manage the code and avoid any redundancy. The super() function enables seamless access to the attributes and the methods within the subclass.