本文摘自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语言的编程模式有什么
Python中线程与进程的区别与优劣
浅谈Python中的排序
Python是面向过程的吗
Python序列循环移位的3种方法
Python怎么读csv文件
Python基于numpy模块创建对称矩阵的方法
Python视频爬虫实现下载头条视频
Python如何产生20个随机整数
Python中的数怎么实现逆序
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » 使用 if x is not None 还是if not x is None