Discuss / Python / 关于 None 的类型:NoneType 的不解

关于 None 的类型:NoneType 的不解

我的环境: windows7 python 2.7

遇到了一个不解的问题,情况如下: 我使用:

type(None)

这条语句,返回的是:

NoneType

而当我使用:

isinstance(None, NoneType)

时却报错,提示:NameError:name ‘NoneType’ is not defined。


问题:

1.为什么会出现如上的情况。如果我用isinstance([1,2,3], list)的方式去验证一个list行得通,那么为什么验证None时就不行了。

2.如果我希望使用类似 isinstance 的方式去验证一个变量是否是None,我该怎么做。

谢谢~

list是内置类型,None类型定义在types module里,所以要需要import这个module

$ from types import NoneType

$ isinstance(None, NoneType) True

多谢大宝儿~ 答案简练有效!

廖雪峰

#4 Created at ... [Delete] [Delete and Lock User]

判断None:

x is None

x is not None

  • 1

Reply