Isinstance() Function in Python

In Python, the isinstance() function is used to check if an object is an instance of a specific class.

Syntax

isinstance(object, class)

The function takes two parameters:

  • The object you want to check.
  • The class you want to verify against.

It returns a boolean value:

  • True: If the object is an instance of the specified class.
  • False: If the object is not an instance of the specified class.

    A Practical Example

    Here’s a simple script where I define two classes.

    I then create an instance of the first class (Classe1) and assign it to the variable var.

    1. class Classe1(object):
    2. def metodo1(self):
    3. print('A')
    4. class Classe2(object):
    5. def metodo1(self):
    6. print('B')
    7. var = Classe1()

    Next, I use the isinstance() function to determine if var is an instance of Classe1.

    The function returns True as expected:

    >>> isinstance(var, Classe1)
    >>> True

    This confirms that var is indeed an instance of Classe1.

    Now, let’s check if var is an instance of the second class, Classe2.

    >>> isinstance(var, Classe2)
    >>> False

    Here, the function returns False, as var is not an instance of Classe2.

    And so on.

     
     

    Please feel free to point out any errors or typos, or share suggestions to improve these notes. English isn't my first language, so if you notice any mistakes, let me know, and I'll be sure to fix them.

    FacebookTwitterLinkedinLinkedin
    knowledge base

    Python Classes