Python isinstance() Function
Description
The isinstance() function determines whether an object is of a known type, similar to type().
Differences between isinstance() and type():
type() does not consider a subclass to be a type of its parent class; it does not take inheritance into account.
isinstance() considers a subclass to be a type of its parent class; it takes inheritance into account.
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 -- the object instance.
- classinfo -- can be a direct or indirect class name, a basic type, or a tuple of them.
Return Value
Returns True if the object's type matches the type of the second parameter (classinfo), otherwise returns False.
Example
The following examples demonstrate the use of 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 elements in 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
Python built-in function