python中的none

來源:互聯網
上載者:User

標籤:情況   判斷   作者   erp   operation   including   log   ted   following   

None是一個對象,其類型為NoneType,其bool值為false,好比0是一個對象,其類型為int,其bool值為false,而在Python中bool值為false的有以下幾種:

靈劍

連結:https://www.zhihu.com/question/48707732/answer/112233903
來源:知乎
著作權歸作者所有。商業轉載請聯絡作者獲得授權,非商業轉載請註明出處。

這個其實在Python文檔當中有寫了,為了準確起見,我們先引用Python文檔當中的原文:
In the context of Boolean operations, and also when expressions are used bycontrol flow statements, the following values are interpreted as false:False, None, numeric zero of all types, and empty strings and containers(including strings, tuples, lists, dictionaries, sets and frozensets). Allother values are interpreted as true. (See the __nonzero__()special method for a way to change this.)

進行邏輯判斷(比如if)時,Python當中等於False的值並不只有False一個,它也有一套規則。對於基本類型來說,基本上每個類型都存在一個值會被判定為False。大致是這樣:
  1. 布爾型,False表示False,其他為True
  2. 整數和浮點數,0表示False,其他為True
  3. 字串和類字串類型(包括bytes和unicode),Null 字元串表示False,其他為True
  4. 序列類型(包括tuple,list,dict,set等),空表示False,非空表示True
  5. None永遠表示False

自訂類型的對象則服從下面的規則:

  1. 如果定義了__nonzero__()方法,會調用這個方法,並按照傳回值判斷這個對象等價於True還是False
  2. 如果沒有定義__nonzero__方法但定義了__len__方法,會調用__len__方法,當返回0時為False,否則為True(這樣就跟內建類型為空白時對應False相同了)
  3. 如果都沒有定義,所有的對象都是True,只有None對應False
 1 >>> class a: 2     def __nonzero__(self): 3         return 0 4  5      6 >>> b = a() 7 >>> if b: 8     print "haha" 9 10     11 >>> if not b:12     print "haha"13 14     15 haha16 >>> if a:17     print "haha"18 19     20 haha

 


所以準確來說,你的這句(state是字典,get方法是判斷字典中的鍵中有沒有第一個參數,沒有返回第二個參數)

state = states.get(‘texas‘, None)if not state:    ....

等價於

if ‘texas‘ not in states or states[‘texas‘] is None or not states[‘texas‘]:    ...

它有三種成立的情況:

  1. dict中不存在
  2. dict中存在,但值是None
  3. dict中存在而且也不是None,但是是一個等同於False的值,比如說Null 字元串或者空列表。

 

 

python中的none

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.