Python isinstance() With Examples

Python isinstance() function is used to check if an object is an instance of the specified class or not.

Python isinstance()

Python isinstance() function syntax is:

This function returns True if the object is instance of classinfo argument or instance of classinfo subclass.

If the object is not an instance of classinfo or its subclass, then the function returns False.

classinfo argument can be a tuple of types. In that case, isinstance() will return True if the object is an instance of any of the types.

If classinfo is not a type or tuple of types, a TypeError exception is raised.

Python isinstance() example

Let’s look at some simple examples of isinstance() function with built-in data types, such as string, tuple, list, dict, bytes etc.

Python isinstance() number

Output:

Python isinstance() string

Output:

Python isinstance() bytes

Output:

Python isinstance() tuple

Output:

Python isinstance() list

Output:

Python isinstance() dict

Output:

Python isinstance() class and inheritance

Let’s look at an example of isinstance() function with custom class and inheritance with multiple classes.

Output:

Python isinstance() tuple of classes

Output:

Summary

Python isinstance() is a utility function to check if an object is of a specific type or not. We can use it to perform a type check and perform operations based on the type of object.

You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: Official Documentation

By admin

Leave a Reply