谷歌的作风指南和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的细致内容,更多请关注ki4网别的相干文章!