Thursday, January 20, 2022

Python Type Isinstance

Python Type Isinstance

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.
type in Python

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 in Python

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

(continued...)

from Planet SciPy
read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...