Py学习  »  Python

[精华] python 中 if not x: 引来的一些问题笔记

爱情的枪 • 10 年前 • 13202 次点击  

代码中经常会有变量是否为None的判断,有三种主要的写法:

  • 第一种是if x is None
  • 第二种是 if not x:
  • 第三种是if not x is None(这句这样理解更清晰if not (x is None)) 。

如果你觉得这样写没啥区别,那么你可就要小心了,这里面有一个坑。先来看一下代码:

>>> x = 1  
>>> not x  
False  
>>> x = [1]  
>>> not x  
False  
>>> x = 0  
>>> not x  
True  
>>> x = [0]         # You don't want to fall in this one.  
>>> not x  
False

在python中 None, False, 空字符串"", 0, 空列表[], 空字典{}, 空元组()都相当于False ,即:

not None == not False == not '' == not 0 == not [] == not {} == not ()

对于习惯于使用if not x这种写法的pythoner,必须清楚x等于None, False, 空字符串"", 0, 空列表[], 空字典{}, 空元组()时对你的判断没有影响才行。

而对于if x is not Noneif not x is None写法,很明显前者更清晰,而后者有可能使读者误解为if (not x) is None,因此推荐前者,同时这也是谷歌推荐的风格

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/397
 
13202 次点击  
文章 [ 1 ]  |  最新文章 10 年前
三画儿
Reply   •   1 楼
三画儿    10 年前

可以给个赞嘛 :)