python 中 "if x is not None" 和 "if not x is None" 有什么区别?
伊谢尔伦
伊谢尔伦 2017-04-17 13:36:45
0
6
999

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?

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

全部回覆(6)
Ty80

內容和標題不符,if xif not x is None 是不一樣的。

if x 會對x做 __nonzero__ 判斷,當 x 為 ''(空字串),{}(空字典), 0 的時候都是 False。當你確實要判斷一個變數不是 None 的時候,應該用 if x is not None

至於 if not x is Noneif 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 Noneif not x is None更易讀,畢竟英文當中有一個 isn't 呢。

PHPzhong

if not x is Noneif x is not None 對電腦而言是一樣的。對人類而言是不一樣的。

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

洪涛

前者更pythonic

洪涛

假如原本你的xNone
你要執行以下程式碼判斷x是否已經改變,仍為None

x = False
if x:
    print 'yes'
else:
    print 'no'

你得到會是 no ,其實 x 已經被改變了,但還是False

if not x is Noneif x is not None 結果是一樣的。

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

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!