Python isinstance() Function

Python isinstance() function is used to check whether the given object is an instance of that class. If the object belongs to the class, it returns True. Otherwise returns False. It also returns true if the class is a subclass.

The isinstance() function takes two arguments object and classinfo and returns either True or False. The signature of the function is given below.

Syntax:

Parameters

object: It is an object of string, int, float, long or custom type.

classinfo: Class name.

Return

It returns boolean either True or False.

Let's see some examples of isinstance() function to understand it's functionality.

Python Isinstance() Examples:

We utilize the isinstance() function to check whether various variables are instances of their separate data types or classes.

1. Integer

Code

Output:

True

2. Float

Code

Output:

True

3. String

Code

Output:

True

4. List

Code

Output:

True

5. Dictionary

Code

Output:

True

6. Tuple

Code

Output:

True

7. Set

Code

Output:

True

8. Class

Code

Output:

True

Let's see some more examples of isinstance() function to understand it's functionality.

Python isinstance() Function Example 1

Here, we are passing object and class to the function which returns True only if the object belongs to the class. See the below example.

Code

Output:

True
False

Python isinstance() Function Example 2

isinstance() can be utilized to check on the off chance that an object is an instance of a class that carries out a specific interface. We can characterize an interface as a class that determines a bunch of techniques that different classes execute.

Code

Output:

"Woof!"
"Meow!"

Python isinstance() Function Example 3

This function also returns True if the object is of subclass and class is a parent class. See, how it works in the below example.

Code

Output:

True
True

Conclusion:

In conclusion, the isinstance() function is a helpful built-in Python function that permits us to check whether an object is an instance of a predefined class or subclass. This can be especially valuable while working with code that includes various data types, or while writing libraries or APIs that need to deal with a great many input types. By utilizing isinstance(), one can guarantee that our code acts accurately for different input types and is more vigorous generally speaking.






Latest Courses