1. 程式人生 > >python中的none

python中的none

sta nor 都是 nonetype 字符 get方法 對象 pes ner

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 by control 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). All other 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),空字符串表示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 haha 16 >>> if a: 17 print "haha" 18 19 20 haha


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

state = states.get‘texas‘Noneif 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的值,比如說空字符串或者空列表。

python中的none