issubclass() Built-in Function


Python - issubclass()

Python issubclass() built-in function is used to check if an object is an instance of specified class.

In this tutorial, we will learn the syntax and usage of isinstance() built-in function with examples.

Syntax

The syntax of isinstance() function is

isinstance(object, classinfo)

where

ParameterMandatory/
Optional
Description
objectOptionalA function for getting the attribute value.
classinfoOptionalA function for setting the attribute value.

Examples

1. Check if given object is an instance of specific class

In the following program, we define two classes: Person and Student. We define Student class such that it is a sub class of Person class. And, we programmatically check that using issubclass() built-in function.

Python Program

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

class Student(Person):
    marks=0
    def printDetails(self):
        print(f"Name: {self.name}\nAge: {self.age}\nMarks: {self.marks}")
        
if issubclass(Student, Person):
    print(f"Student is a sub class of Person.")
else:
    print(f"Student is not a sub class of Person.")

Output

Student is a sub class of Person.

2. Negative Scenario

In the following program, we consider the same two classes from the above program. And we check if Person class is a subclass of list built-in class, or not. Since, we know that is not the case, issubclass() must return False, and else-block must execute.

Python Program

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

class Student(Person):
    marks=0
    def printDetails(self):
        print(f"Name: {self.name}\nAge: {self.age}\nMarks: {self.marks}")

if issubclass(Person, list):
    print(f"Person is a sub class of list class.")
else:
    print(f"Person is not a sub class of list class.")

Output

Person is not a sub class of list class.

Summary

In this Built-in Functions tutorial, we learned the syntax of the issubclass() built-in function, and how to use this function to check if given class is a sub class of other specified class.