The isinstance() function returns true if the first argument of the function is an instance or subclass of the second argument. Actually, we can say that this function is used to check the given object is an instance or subclass of the given class.
isinstance(object, classinfo) # Where object specify name of the object
Takes 2 parameters where a first parameter is an object of string, int, float, long, or custom type.
Parameter | Description | Required / Optional |
---|---|---|
object | An object to be checked. | Required |
classinfo | The class name or a tuple of class names. | Required |
It returns a boolean value either true or false.
Input | Return Value |
---|---|
an object is an instance | true |
an object is not an instance | false |
classinfo is not a type or tuple of types | TypeError exception |
class Foo:
a = 5
fooInstance = Foo()
print(isinstance(fooInstance, Foo))
print(isinstance(fooInstance, (list, tuple)))
print(isinstance(fooInstance, (list, tuple, Foo)))
Output:
True False True
numbers = [1, 2, 3]
result = isinstance(numbers, list)
print(numbers,'instance of list?', result)
result = isinstance(numbers, dict)
print(numbers,'instance of dict?', result)
result = isinstance(numbers, (dict, list))
print(numbers,'instance of dict or list?', result)
number = 5
result = isinstance(number, list)
print(number,'instance of list?', result)
result = isinstance(number, int)
print(number,'instance of int?', result)
Output:
[1, 2, 3] instance of list? True [1, 2, 3] instance of dict? False [1, 2, 3] instance of dict or list? True 5 instance of list? False 5 instance of int? True
# Python isinstance() function example
class Student:
id = 101
name = "John"
def __init__(self, id, name):
self.id=id
self.name=name
student = Student(1010,"John")
lst = [12,34,5,6,767]
# Calling function
print(isinstance(student, Student)) # isinstance of Student class
print(isinstance(lst, Student))
Output:
True False