Python isinstance() function with example

Hello readers, we will be discussing isinstance() function used in the Python programming language to check whether or not the object is instance or subclass of another object. This function simply returns the output in Boolean value (i.e either True or False ).

Thus as per the definition, you must have got an idea of exactly what work does the isinstance() function does, if you are familiar with classes and functions in Python. The following syntax will provide a better idea of isinstance() function :

Syntax:
isinstance(object , ClassInfo)
here,
object: object is the value to be checked . &
ClassInfo: Class type to be determined  (list,tuple etc)

If classinfo is not a class type then we can get TypeError

Examples for isinstance() function in Python:

These following examples are some basics example for understanding of the function:

  1. Determining whether a variable is Integer or not :
    isinstance(2 , int)

    The Output for the above line of code will be
    Output :

    True 
    
    

    Thus from the above Output, we see that we are using an object as 2, & class info here is int(integer) and the output returned is True i.e  2 is the integer
    similarly, we can say do this for tuples  too

  2. Determining the object is type of tuple or not
    list1 = [10,20,'a']
    print(isinstance(list1, tuple))

    Output:

    False
    
    

    The output here is False because the object list1 is not the in form of tuple instead it is a type of list and we have checked is as the type of tuple

  3. Now let’s create the user-defined class and check its object is a type of the class or not
    class Myclass :
        a = 9
    obj1 = Myclass()
    print(isinstance(obj1, Myclass))

    Output :

    True

    So here we have created the class Myclass and added a variable value a = 2, and  created an object to define a class and checked the object whether it is instance r subclass of Myclass or not  by using isinstance function and out we got is true so obj1 is an instance of class Myclass.

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *