python中if not x_python使用 'if x is not None' 还是'if not x is None' – IT热血青年

今天爱分享给大家带来python使用 ‘if x is not None’ 还是’if not x is 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’

如果写作 ‘x is not y’ 就不会有歧义

最佳实践

if x is not None:

# Do something about x

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值