- A subclass in Python specializes one or more base classes. The subclass derives certain functionalities from the base classes but it has its own special features than that of the base class.
- If the subclass B is derived from class A, B is a direct subclass of A.
- If class C is derived from class B which is derived from class A, then class C is an indirect subclass of B.
- If X is a class that has specialised methods which a developer deems fit to consider as a classification under the class A(given A is an abstract class), then this classification is called virtual inheritance in Python.
- Given a class name the built-in function issubclass() determines whether it is a subclass of another class. The subclass could be a direct, indirect or a virtual subclass.
Example 1 - Checks a direct subclass is derived from a base class:
# Example Python program that checks whether a direct subclass is
# class definition of Rover
# class defintion of ForestRover
def move(self, direction):
# Create an instance of a ForestRover
# Check whether ForestRover is a subclass of Rover
# Perform some rover operations
Forest rover is derived from Rover:True
Forest rover is on
Forest rover moving in forward
Forest rover turning right
Forest rover is off
Example 2 - Checks an indirect subclass is derived from a base class:
mlRover = MarshlandRover(1.0)
MarshlandRover is derived from Rover:True
Example 3 - Checks whether a virtual subclass is a subclass through issubclass():
# Example Python program that checks whether
# Create an abstract base class (i.e., A rover interface)
# An independent mars rover not part of rover hierarchy
# An independent mars water rover not part of rover hierarchy
# Make the MarsRover part of Rover hierarchy
isARover = issubclass(MarsRover, Rover)
# Since MarsRover has been registered in the rover hierarchy
Is MarsRover a Rover:False
Is MarsRover a Rover:True
Is MarsWaterRover a Rover:True