本文摘自php中文网,作者anonymity,侵删。
使用 if x is not None 还是if not x is None呢?谷歌的风格指南和PEP-8都使用if x is not None,那么它们之间是否存在某种轻微的性能差异呢?

通过测试发现没有性能差异,因为它们编译为相同的字节码:
1 2 3 4 5 6 7 8 9 | 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就没有这些歧义。
以上就是使用 if x is not None 还是if not x is None的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
Python中matplotlib库的用法介绍
Python爬虫可以自学吗
Python docx 中文字体设置的操作方法
windows下Python连接oracle数据库实例方法
如何用Python做游戏
Python numpy 点数组去重
Python 3.6 读取并操作文件内容
Python怎么发音
pandas series对象的常见属性有哪些?
如何使用Python中range()方法?
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » 使用 if x is not None 还是if not x is None