日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python中if not是什么意思,python if not不同应用有什么区别,pythonifnot区别,python 中 "if...

發(fā)布時間:2025/5/22 python 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python中if not是什么意思,python if not不同应用有什么区别,pythonifnot区别,python 中 "if... 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

python if not不同應(yīng)用有什么區(qū)別,pythonifnot區(qū)別,python 中 "if

python 中 "if x is not None" 和 "if not x is None" 有什么區(qū)別?

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結(jié)果不是,後者是x不該是None結(jié)果也不是。個人感覺,無客觀依據(jù)(好像沒有人做這樣的心理實驗?)。

前者更pythonic

內(nèi)容和標題不符,if x 和 if not x is None 是不一樣的。

if x 會對x做 __nonzero__ 判斷,當 x 為 ''(空字符串),{}(空字典), 0 的時候都是 False。當你確實要判斷一個變量不是 None 的時候,應(yīng)該用 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

你要執(zhí)行如下代碼判斷x是否已經(jīng)發(fā)生改變,仍為None?x = Falseif x: print 'yes'else: print 'no'

你得到會是 no ,其實 x 已經(jīng)被改變了,但仍然是False

if not x is None 和 if x is not None 結(jié)果是一樣的。

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

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

編橙之家文章,

《新程序員》:云原生和全面數(shù)字化實踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀

總結(jié)

以上是生活随笔為你收集整理的python中if not是什么意思,python if not不同应用有什么区别,pythonifnot区别,python 中 "if...的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。