The isinstance() function in Python allows checking if an object is of the specified type. In other words, it will check if the 1st parameter is a subclass of the 2nd parameter. If it matches it will return True, otherwise, it will return False.
Here at LinuxAPT, we shall look into how to use the isinstance() function in Python.
If an object is of the specified type, this function will return True, otherwise, it will return False.
The case the parameter is of type tuple, if the object is one of type tuple, it will return True.
It's syntax is given below:
isinstance(object, type)
Python isinstance() Function Parameter Values:
1. Have a look at the below function:
x = isinstance(1, int)
print(x)
It's Output will give :
True
2. Another example is given below:
x = isinstance(1, float)
print(x)
It's Output will give:
False
3. Another example:
class NAME:
name = "BEND"
z = NAME()
x = isinstance(z, NAME)
print(x)
The Output will give:
True
4. Check this function:
class Foo:
a = 5
fooInstance = Foo()
print(isinstance(fooInstance, Foo))
print(isinstance(fooInstance, (list, tuple)))
print(isinstance(fooInstance, (list, tuple, Foo)))
The Output will give:
True
False
True
5. This last one:
testlist = [1, 2, 3]
print(isinstance(testlist, list))
The Output will give:
True
This article covers how to use the isinstance() function in Python. In fact, the isinstance() function checks if the object (first argument) is an instance or subclass of classinfo class (second argument).
isinstance Return Value
isinstance() returns:
If classinfo is not a type or tuple of types, a TypeError exception is raised.