Python - Differentiate Between type() and isinstance()
In Python, type()
and isinstance()
are two built-in functions used to check the type of an object. However, they differ in the way they determine the type of an object.
type()
returns the type of the object as a built-in type. It returns the exact type of the object, such as int
, float
, str
, list
, dict
, tuple
, etc. For example:
x = 5 print(type(x)) # Output: <class 'int'>
In the above example, type(x)
returns the built-in type int
.
On the other hand, isinstance()
is used to check whether an object is an instance of a particular class or not. It returns True
if the object is an instance of the specified class or a subclass of it, and False
otherwise. For example:
x = 5 print(isinstance(x, int)) # Output: True
In the above example, isinstance(x, int)
returns True
because x
is an instance of the int
class.
Here's another example to demonstrate the difference between type()
and isinstance()
:
class MyClass: pass obj = MyClass() print(type(obj)) # Output: <class '__main__.MyClass'> print(isinstance(obj, MyClass)) # Output: True
In this example, we define a class MyClass
and create an instance of it named obj
. type(obj)
returns <class '__main__.MyClass'>
, which is the exact type of the object. isinstance(obj, MyClass)
returns True
because obj
is an instance of the MyClass
class.
In summary, the type()
function returns the exact type of an object, while the isinstance()
function checks whether an object is an instance of a specified class or not.