How to Check If a Class Is a Subclass of Another in Python

PythonPythonBeginner
Practice Now

Introduction

In this lab, you will learn how to check if a class is a subclass of another class in Python. This involves exploring class inheritance, a fundamental concept in object-oriented programming.

You'll begin by creating a parent class Animal with a constructor and a speak method. Then, you'll create child classes Dog and Cat that inherit from Animal and override the speak method. Finally, you will learn how to use issubclass() function and inspect __bases__ attribute to determine subclass relationships.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/ObjectOrientedProgrammingGroup(["Object-Oriented Programming"]) python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") python/ObjectOrientedProgrammingGroup -.-> python/classes_objects("Classes and Objects") python/ObjectOrientedProgrammingGroup -.-> python/inheritance("Inheritance") subgraph Lab Skills python/build_in_functions -.-> lab-559501{{"How to Check If a Class Is a Subclass of Another in Python"}} python/classes_objects -.-> lab-559501{{"How to Check If a Class Is a Subclass of Another in Python"}} python/inheritance -.-> lab-559501{{"How to Check If a Class Is a Subclass of Another in Python"}} end

Explore Class Inheritance

In this step, you will learn about class inheritance, a fundamental concept in object-oriented programming (OOP). Inheritance allows you to create new classes (child classes) that inherit attributes and methods from existing classes (parent classes). This promotes code reuse and helps in building more organized and maintainable code.

Let's start by creating a simple parent class called Animal:

## Create a file named animal.py in the ~/project directory
class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        print("Generic animal sound")

Open your VS Code editor and create a new file named animal.py in the ~/project directory. Copy and paste the above code into the file. This class has an __init__ method (constructor) that initializes the name attribute and a speak method that prints a generic animal sound.

Now, let's create a child class called Dog that inherits from the Animal class:

## Add the following code to animal.py
class Dog(Animal):
    def speak(self):
        print("Woof!")

Add the above code to the animal.py file. The Dog class inherits from Animal by specifying Animal in parentheses after the class name. The Dog class also overrides the speak method to provide its own specific implementation.

Next, let's create another child class called Cat that also inherits from the Animal class:

## Add the following code to animal.py
class Cat(Animal):
    def speak(self):
        print("Meow!")

Add the above code to the animal.py file. The Cat class also inherits from Animal and overrides the speak method.

Now, let's create a main program to use these classes:

## Create a file named main.py in the ~/project directory
from animal import Animal, Dog, Cat

animal = Animal("Generic Animal")
dog = Dog("Buddy")
cat = Cat("Whiskers")

animal.speak()
dog.speak()
cat.speak()

Create a new file named main.py in the ~/project directory and copy and paste the above code into the file. This program imports the Animal, Dog, and Cat classes from the animal.py file. It then creates instances of each class and calls their speak methods.

To run the program, open your terminal in VS Code and navigate to the ~/project directory:

cd ~/project

Then, execute the main.py script using the python command:

python main.py

You should see the following output:

Generic animal sound
Woof!
Meow!

This demonstrates how the Dog and Cat classes inherit from the Animal class and provide their own specific implementations of the speak method. This is a basic example of class inheritance in Python.

Use issubclass() Function

In this step, you will learn how to use the issubclass() function to check if a class is a subclass of another class. This function is a built-in Python function that returns True if the first argument is a subclass of the second argument, and False otherwise.

Continuing with the example from the previous step, let's use the issubclass() function to check the relationships between the Animal, Dog, and Cat classes.

Open your VS Code editor and create a new file named issubclass_example.py in the ~/project directory. Copy and paste the following code into the file:

## Create a file named issubclass_example.py in the ~/project directory
from animal import Animal, Dog, Cat

print(issubclass(Dog, Animal))
print(issubclass(Cat, Animal))
print(issubclass(Dog, Cat))
print(issubclass(Animal, Dog))
print(issubclass(Animal, Animal))

This program imports the Animal, Dog, and Cat classes from the animal.py file you created in the previous step. It then uses the issubclass() function to check the following relationships:

  • Is Dog a subclass of Animal?
  • Is Cat a subclass of Animal?
  • Is Dog a subclass of Cat?
  • Is Animal a subclass of Dog?
  • Is Animal a subclass of Animal?

To run the program, open your terminal in VS Code and navigate to the ~/project directory:

cd ~/project

Then, execute the issubclass_example.py script using the python command:

python issubclass_example.py

You should see the following output:

True
True
False
False
True

This output shows that:

  • Dog is a subclass of Animal (True)
  • Cat is a subclass of Animal (True)
  • Dog is not a subclass of Cat (False)
  • Animal is not a subclass of Dog (False)
  • Animal is a subclass of itself (True)

The issubclass() function is useful for checking the inheritance relationships between classes in your code. This can be helpful for ensuring that your code is behaving as expected and for writing more robust and maintainable code.

Inspect bases Attribute

In this step, you will learn how to inspect the __bases__ attribute of a class to find its direct parent classes. The __bases__ attribute is a tuple that contains the parent classes of a class.

Continuing with the example from the previous steps, let's inspect the __bases__ attribute of the Animal, Dog, and Cat classes.

Open your VS Code editor and create a new file named bases_example.py in the ~/project directory. Copy and paste the following code into the file:

## Create a file named bases_example.py in the ~/project directory
from animal import Animal, Dog, Cat

print(Dog.__bases__)
print(Cat.__bases__)
print(Animal.__bases__)

This program imports the Animal, Dog, and Cat classes from the animal.py file you created in the previous steps. It then prints the __bases__ attribute of each class.

To run the program, open your terminal in VS Code and navigate to the ~/project directory:

cd ~/project

Then, execute the bases_example.py script using the python command:

python bases_example.py

You should see the following output:

(<class 'animal.Animal'>,)
(<class 'animal.Animal'>,)
(<class 'object'>,)

This output shows that:

  • The Dog class inherits from the Animal class.
  • The Cat class inherits from the Animal class.
  • The Animal class inherits from the object class, which is the base class for all classes in Python.

The __bases__ attribute is useful for understanding the inheritance hierarchy of your classes. This can be helpful for debugging and for writing more maintainable code.

Summary

In this lab, you explored class inheritance in Python, a key concept in object-oriented programming. You created a parent class Animal with a constructor and a speak method, and then defined child classes Dog and Cat that inherited from Animal.

These child classes overrode the speak method to provide their own specific implementations, demonstrating how inheritance allows for code reuse and specialization. Finally, you created instances of these classes and called their speak methods to observe the different outputs.