python if not用法_python if not不同应用有什么区别

python 中 "if x is not None" 和 "if not x is None" 有什么区别?

google 的 python 风格指南中这么说:

Beware of writing if x: when you really mean if x is not None:—e.g., when testing whether a variable or argument that defaults to None was set to some other value. The other value might be a value that's false in a boolean context!

也就是说,推荐使用 if x is not None 进行判断,but why?

if not x is None 和 if x is not None 對計算機而言是一樣的。對人類而言是不一樣的。

前者的隱含意義是x本該是None結果不是,後者是x不該是None結果也不是。個人感覺,無客觀依據(好像沒有人做這樣的心理實驗?)。

前者更pythonic

内容和标题不符,if x 和 if not x is None 是不一样的。

if x 会对x做 __nonzero__ 判断,当 x 为 ''(空字符串),{}(空字典), 0 的时候都是 False。当你确实要判断一个变量不是 None 的时候,应该用 if x is not None。

至于 if not x is None 和 if x is not None 是一样的,选一个你读的顺的就好。

前者更接近白话文,而后者有可能使读者误解为if (not x) is None.

首先,直接查看操作码(XP+Python3.4)。

x is not None的操作码:dis.dis('if x is not None: pass')

0 LOAD_NAME 0 (x)

3 LOAD_CONST 0 (None)

6 COMPARE_OP 9 (is not)

9 POP_JUMP_IF_FALSE 15

12 JUMP_FORWARD 0 (to 15)

>> 15 LOAD_CONST 0 (None)

18 RETURN_VALUE

if not x is None的操作码:dis.dis('if not x is None: pass')

0 LOAD_NAME 0 (x)

3 LOAD_CONST 0 (None)

6 COMPARE_OP 9 (is not)

9 POP_JUMP_IF_FALSE 15

12 JUMP_FORWARD 0 (to 15)

>> 15 LOAD_CONST 0 (None)

18 RETURN_VALUE

可以看到,操作码是一样的!

题主还可以测试后面加or或者and的情况。

个人意见,if x is not None比if not x is None更加易读,毕竟英语当中有一个 isn't 呢。

假如原本你的x为None

你要执行如下代码判断x是否已经发生改变,仍为None?x = False

if x:

print 'yes'

else:

print 'no'

你得到会是 no ,其实 x 已经被改变了,但仍然是False

if not x is None 和 if x is not None 结果是一样的。

if not x is None => if not (x is None)

if x is not None => if x (is not) None

玩蛇网文章,转载请注明出处和文章网址:https://www.iplaypy.com/wenda/wd19338.html

相关文章 Recommend

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值