python代碼 if not x: 和 if x is not None: 和 if not x is None:使用介紹,pythonnone

來源:互聯網
上載者:User

python代碼 if not x: 和 if x is not None: 和 if not x is None:使用介紹,pythonnone

代碼中經常會有變數是否為None的判斷,有三種主要的寫法:
第一種是`if x is None`;
第二種是 `if not x:`;
第三種是`if not x is None`(這句這樣理解更清晰`if not (x is None)`) 。
如果你覺得這樣寫沒啥區別,那麼你可就要小心了,這裡面有一個坑。先來看一下代碼:

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

在python中 None, False, Null 字元串"", 0, 空列表[], 空字典{}, 空元組()都相當於False ,即:

複製代碼 代碼如下:
not None == not False == not '' == not 0 == not [] == not {} == not ()

因此在使用列表的時候,如果你想區分x==[]和x==None兩種情況的話, 此時`if not x:`將會出現問題:

>>> x = []>>> y = None>>> >>> x is NoneFalse>>> y is NoneTrue>>> >>> >>> not xTrue>>> not yTrue>>> >>> >>> not x is None>>> True>>> not y is NoneFalse>>> 

也許你是想判斷x是否為None,但是卻把`x==[]`的情況也判斷進來了,此種情況下將無法區分。
對於習慣於使用if not x這種寫法的pythoner,必須清楚x等於None, False, Null 字元串"", 0, 空列表[], 空字典{}, 空元組()時對你的判斷沒有影響才行。
而對於`if x is not None`和`if not x is None`寫法,很明顯前者更清晰,而後者有可能使讀者誤解為`if (not x) is None`,因此推薦前者,同時這也是Google推薦的風格

結論:
`if x is not None`是最好的寫法,清晰,不會出現錯誤,以後堅持使用這種寫法。
使用if not x這種寫法的前提是:必須清楚x等於None, False, Null 字元串"", 0, 空列表[], 空字典{}, 空元組()時對你的判斷沒有影響才行。

================================================================
不過這並不適用於變數是函數的情況,以下轉載自:https://github.com/wklken/stackoverflow-py-top-qa/blob/master/contents/qa-control-flow.md

foo is None 和 foo == None的區別

問題 連結

if foo is None: pass
if foo == None: pass

如果比較相同的對象執行個體,is總是返回True 而 == 最終取決於 "eq()"

>>> class foo(object):  def __eq__(self, other):    return True>>> f = foo()>>> f == NoneTrue>>> f is NoneFalse>>> list1 = [1, 2, 3]>>> list2 = [1, 2, 3]>>> list1==list2True>>> list1 is list2False

另外

(ob1 is ob2) 等價於 (id(ob1) == id(ob2))

################################################################################
補充,2013.10.09

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.