python中的"is not None"是什么意思?

Nik*_*ntz 3 python-2.7

这两个蟒蛇成语有什么区别?

if data is not None: return data

if data: return data

Jos*_*Lee 11

后者也会拒绝False,0,[],(),{},set(),'',和其他任何值,其__bool__方法返回false,包括最空的集合.

NonePython中的值通常用于表示缺少值.当函数未显式返回值时,它会自动出现.

>>> def f():
...   pass
>>> f() is None
True
Run Code Online (Sandbox Code Playgroud)

它通常用作可选参数的默认值,如:

def sort(key=None):
    if key is not None:
        # do something with the argument
    else:
        # argument was omitted
Run Code Online (Sandbox Code Playgroud)

如果你只if key:在这里使用,则不会考虑评估为false的参数.明确地比较is None是进行此检查的正确习语.请参阅真值测试.