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
Python 3.6.10 :: Anaconda, Inc.
Check if type is Integer
In [1]:
x = 1
In [6]:
print(type(x))
<class 'int'>
Check if type is Float
In [8]:
x = 1.5
In [9]:
print(type(x))
<class 'float'>
Check if type is String
In [10]:
x = 'john'
In [11]:
print(type(x))
<class 'str'>
In [12]:
x = 'j'
In [13]:
print(type(x))
<class 'str'>
Check if type is Class
In [14]:
class demo(): pass
In [22]:
print(type(demo()))
<class '__main__.demo'>
In [23]:
type(demo())==demo
Out[23]:
True
isinstance can be used to check the type of object.
In [24]:
x = 1
In [25]:
isinstance(x,int)
Out[25]:
True
In [26]:
isinstance(x,float)
Out[26]:
False
In [27]:
x = 1.2
In [28]:
isinstance(x,float)
Out[28]:
True
isinstance can check the
from Planet SciPy
read more
No comments:
Post a Comment