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

时间:2013-06-14 21:10:26

标签: python-2.7

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

if data is not None: return data

if data: return data

1 个答案:

答案 0 :(得分:9)

后者还会拒绝False0[](){}set()'',以及__bool__方法返回False的任何其他值,包括大多数空集合。

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

>>> def f():
...   pass
>>> f() is None
True

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

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

如果您在此处仅使用if key:,则不会考虑评估为false的参数。与is None明确比较是进行此检查的正确习惯用语。请参阅Truth Value Testing