为什么“if not someobj:”比Python中的“if someobj == None:”

我见过几个像这样的代码示例:


if not someobj:

    #do something

但我想知道为什么不这样做:


if someobj == None:

    #do something

有什么区别吗?一个人比另一个人有优势吗?


德玛西亚99
浏览 672回答 3
3回答

慕无忌1623718

这些实际上都是不良做法。曾几何时,认为随意对待None和False是相似的。但是,从Python 2.2开始,这不是最好的策略。首先,当你进行一种if x或if not x那种测试时,Python必须隐式转换x为boolean。bool函数的规则描述了一大堆错误的东西; 其他一切都是真的。如果x的值在开始时没有正确的布尔值,那么这种隐式转换实际上并不是最清楚的说法。在Python 2.2之前,没有bool函数,所以它更不清楚。其次,你不应该真的测试== None。你应该使用is None和is not None。请参阅PEP 8,Python代码样式指南。- Comparisons to singletons like None should always be done with  'is' or 'is not', never the equality operators.  Also, beware of writing "if x" when you really mean "if x is not None"  -- e.g. when testing whether a variable or argument that defaults to  None was set to some other value.  The other value might have a type  (such as a container) that could be false in a boolean context!有多少单身人士?五:None,True,False,NotImplemented和Ellipsis。因为你真的不太可能使用NotImplemented或者Ellipsis,你永远不会说if x is True(因为只是if x更清楚),你只会测试None。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python