Python isinstance() Function
Description
The isinstance() function is used to determine whether an object is a known type, similar to type().
Difference between isinstance() and type():
type() does not consider a subclass as a parent class type and does not take inheritance into account.
isinstance() considers a subclass as a parent class type and takes inheritance into account.
If you want to determine whether two types are the same, isinstance() is recommended.
Syntax
The following is the syntax of the isinstance() method:
isinstance(object, classinfo)
Parameters
- object -- instance object.
- classinfo -- can be a direct or indirect class name, a basic type, or a tuple composed of them.
Return Value
Returns True if the object's type matches the type of the second parameter (classinfo), otherwise returns False.
Examples
The following shows examples of using the isinstance function:
>>>a = 2
>>> isinstance (a,int)
True
>>> isinstance (a,str)
False
>>> isinstance (a,(str,int,list)) # Returns True if it is one of the tuple
True
Difference between type() and isinstance():
class A:
pass
class B(A):
pass
isinstance(A(), A) # returns True
type(A()) == A # returns True
isinstance(B(), A) # returns True
type(B()) == A # returns False
Python Built-in Functions