使用 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就没有这些歧义。
以上就是使用 if x is not None 还是if not x is None的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号