在Python中有None
个单例,在某些情况下,它的行为相当奇怪:
>>> a = None
>>> type(a)
<type 'NoneType'>
>>> isinstance(a,None)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types
首先,<type 'NoneType'>
显示None
不是一种类型,但NoneType
是.然而,当您运行isinstance(a,NoneType)
时,它的响应是一个错误:NameError: name 'NoneType' is not defined
现在,考虑到这一点,如果您有一个输入默认设置为None
的函数,并且需要进行判断,那么您将执行以下操作:
if variable is None:
#do something
else:
#do something
是什么原因导致我不能采取以下措施:
if isinstance(variable,None): #or NoneType
#do something
else:
#do something
I am just looking for a detailed explanation so I can better understand this
编辑:很好的应用
假设我想使用isinstance
,这样如果variable
是多种类型,我就可以做一些事情,包括None
:
if isinstance(variable,(None,str,float)):
#do something