与None变量的类型比较

use*_*679 2 python python-3.x nonetype

我知道不建议比较类型,但我有一些代码在if elif系列中执行此操作.但是,我对于None值如何工作感到困惑.

def foo(object)
    otype = type(object)
    #if otype is None: # this doesn't work
    if object is None: # this works fine
        print("yep")
    elif otype is int:
    elif ...
Run Code Online (Sandbox Code Playgroud)

为什么我可以比较is int好等等,但没有is None?types.NoneType似乎在Python 3.2中消失了,所以我无法使用它......

下列

i = 1
print(i)
print(type(i))
print(i is None)
print(type(i) is int)
Run Code Online (Sandbox Code Playgroud)

版画

1
<class 'int'>
False
True
Run Code Online (Sandbox Code Playgroud)

而

i = None
print(i)
print(type(i))
print(i is None)
print(type(i) is None)
Run Code Online (Sandbox Code Playgroud)

版画

None
<class 'NoneType'>
True
False
Run Code Online (Sandbox Code Playgroud)

我觉得None很特别,但是给出了什么?是否NoneType真的存在,或Python的骗我?

And*_*ark 6

你永远不需要比较NoneType,因为None是一个单身人士.如果你有一些obj可能的对象,那None就是obj is None或obj is not None.

你的比较不起作用的原因是它None不是一个类型,它是一个值.它类似于尝试type(1) is 1整数示例.如果你真的想做一个NoneType检查,你可以使用type(obj) is type(None),或者更好isinstance(obj, type(None)).

  • 对象标识实际上是检查类型的正确选择:`type(obj)是SomeType`我建议用于检查*exact*type匹配(非常罕见的要求).在常见的情况下,使用`isinstance()`. (4认同)

Sil*_*Ray 6

None是Python提供的特例单例. NoneType是单例对象的类型. type(i) is None是的False,但type(i) is type(None)应该是真的.