python 判断一个变量的类型是 NoneType

Determining a variable's type is NoneType in python

我想检查一个变量是否属于 NoneType 类型。对于其他类型,我们可以做类似的事情:

    type([])==list

但是对于NoneType,这种简单的方法是不可能的。也就是说,我们不能说 type(None)==NoneType。有替代方法吗?为什么这对某些类型可能而不对其他类型可行?谢谢。

NoneType 恰好不会自动出现在全局范围内。这不是真正的问题。

>>> NoneType = type(None)
>>> x = None
>>> type(x) == NoneType
True
>>> isinstance(x, NoneType)
True

无论如何,进行类型检查都是不寻常的。相反,您应该测试 x is None.

当然可以。

type(None)==None.__class__

True