isinstance() Built-in Function

Python – isinstance()

Python isinstance() 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 a class named Student. We also create an object student1 of type Student. Then programmatically check if this student1 object is an instance of Student class using isinstance() function.

Python Program

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

student1 = Student('Ram', 12, 'Canada')

# Check if student1 is an instance of Student class
if isinstance(student1, Student):
    print('student1 is an instance of Student class.')
else:
    print('student1 is not an instance of Student class.')
Run Code Copy

Output

student1 is an instance of Student class.

2. Check if list object an instance of specific class

In the following program, we define a class named Student. We are a list in x. After that, we programmatically check if this x object is an instance of Student class using isinstance() function.

We already know that x is not an instance of Student class. Therefore the function isinstance() must return False, and else-block must execute.

Python Program

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

# Check if list object x is an instance of Student class
x = ['Hari', 44]
if isinstance(x, Student):
    print('x is an instance of Student class.')
else:
    print('x is not an instance of Student class.')
Run Code Copy

Output

x is not an instance of Student class.

Summary

In this Built-in Functions tutorial, we learned the syntax of the isinstance() built-in function, and how to use this function to check if given object is an instance of specified class, or not.

Related Tutorials

Code copied to clipboard successfully 👍