Erlo

使用 if x is not None 还是if not x is None

2019-05-24 14:01:34 发布   31 浏览  
页面报错/反馈
收藏 点赞
原文:http://www.php.cn/python-tutorials-420124.html
使用 if x is not None 还是if not x is None呢?

谷歌的风格指南和PEP-8都使用if x is not None,那么它们之间是否存在某种轻微的性能差异呢?

通过测试发现没有性能差异,因为它们编译为相同的字节码:

Python 2.6.2 (r262:71600, Apr 15 2009, 07:20:39)>>> import dis>>> def f(x):...    return x is not None...>>> dis.dis(f)
  2           0 LOAD_FAST                0 (x)
              3 LOAD_CONST               0 (None)
              6 COMPARE_OP               9 (is not)
              9 RETURN_VALUE>>> def g(x):...   return not x is None...>>> dis.dis(g)
  2           0 LOAD_FAST                0 (x)
              3 LOAD_CONST               0 (None)
              6 COMPARE_OP               9 (is not)
              9 RETURN_VALUE

但是在使用风格上,尽量避免not x is y。尽管编译器总是将其视为not (x is y),但读者可能会误解构造为(not x) is y。所以if x is not y就没有这些歧义。

登录查看全部

参与评论

评论留言

还没有评论留言,赶紧来抢楼吧~~

手机查看

返回顶部

给这篇文章打个标签吧~

棒极了 糟糕透顶 好文章 PHP JAVA JS 小程序 Python SEO MySql 确认