在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

推荐答案

你可以试试:

>>> variable = None
>>> isinstance(variable,type(None))
True
>>> variable = True
>>> isinstance(variable,type(None))
False

isinstance在这里接受2个参数isinstance(object, classinfo),通过传递None,您将classinfo设置为无,因此出现错误.你需要通过打字.

Python-3.x相关问答推荐

使用Python装载. iso文件

Python根据阈值对数字进行分组

PySpark每毫秒使用先前的值填充数据

我没有';无法理解此TemplateDoesNotExist错误

msg-seviri l1.5本机文件

SQL Server 2022和Python3.10脚本错误

通过 Pandas 通过用户定义函数重命名数据框列

计算文档中所有关键字(单词和多词)出现的频率

来自嵌套字典的完整地址

类不继承时 super() 的用途

删除给定数组中所有元素为True的所有子数组

根据另一个数据帧中的位置从主数据帧中提取子序列

通过最接近的匹配合并两个不同长度的列上的两个数据框

Tkinter IntVar 返回 PY_VAR0 而不是值

日志(log)模块不适用于 Python3

无法在 Windows 8 中使用 Python 3.3 找到 vcvarsall.bat

如何使用 python 库连接到 poloniex.com websocket api

try 在 Windows 10 高 DPI 显示器上解决模糊的 tkinter 文本 + zoom ,但担心我的方法不是 Pythonic 或不安全

无法解码 Python Web 请求

注册 Celery 基于类的任务