Instance and Type both are used to check the type of object. Instance can check the type of subclass too where as type can't.
In [4]:
!python --version
Check if type is Integer
In [1]:
x = 1
In [6]:
print(type(x))
Check if type is Float
In [8]:
x = 1.5
In [9]:
print(type(x))
Check if type is String
In [10]:
x = 'john'
In [11]:
print(type(x))
In [12]:
x = 'j'
In [13]:
print(type(x))
Check if type is Class
In [14]:
class demo():
pass
In [22]:
print(type(demo()))
In [23]:
type(demo())==demo
Out[23]:
isinstance can be used to check the type of object.
In [24]:
x = 1
In [25]:
isinstance(x,int)
Out[25]:
In [26]:
isinstance(x,float)
Out[26]:
In [27]:
x = 1.2
In [28]:
isinstance(x,float)
Out[28]:
isinstance can check the type of subclass too.
In [29]:
class computer():
pass
class laptop(computer):
pass
In [31]:
isinstance(computer(),computer)
Out[31]:
In [32]:
isinstance(laptop(),computer)
Out[32]:
Note, type can not check the type of subclass.
In [33]:
type(laptop())==computer
Out[33]:
Related Notebooks
- Merge and Join DataFrames with Pandas in Python
- How To Analyze Wikipedia Data Tables Using Python Pandas
- Polynomial Interpolation Using Python Pandas Numpy And Sklearn
- Python If Not
- Understanding Logistic Regression Using Python
- Understanding Standard Deviation With Python
- How To Install Python With Conda
- Object Oriented Programming In Python
- How To Take Integer Input From Command Line In Python