为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

德玛西亚99 2019-09-18 19:34:37
我见过几个像这样的代码示例:if not someobj:    #do something但我想知道为什么不这样做:if someobj == None:    #do something有什么区别吗?一个人比另一个人有优势吗?
查看完整描述

3 回答

?
慕无忌1623718

TA贡献1744条经验 获得超4个赞

这些实际上都是不良做法。曾几何时,认为随意对待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。


查看完整回答
反对 回复 2019-09-18
  • 3 回答
  • 0 关注
  • 676 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信