標籤:情況 判斷 作者 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。大致是這樣:
- 布爾型,False表示False,其他為True
- 整數和浮點數,0表示False,其他為True
- 字串和類字串類型(包括bytes和unicode),Null 字元串表示False,其他為True
- 序列類型(包括tuple,list,dict,set等),空表示False,非空表示True
- None永遠表示False
自訂類型的對象則服從下面的規則:
- 如果定義了__nonzero__()方法,會調用這個方法,並按照傳回值判斷這個對象等價於True還是False
- 如果沒有定義__nonzero__方法但定義了__len__方法,會調用__len__方法,當返回0時為False,否則為True(這樣就跟內建類型為空白時對應False相同了)
- 如果都沒有定義,所有的對象都是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‘]: ...
它有三種成立的情況:
- dict中不存在
- dict中存在,但值是None
- dict中存在而且也不是None,但是是一個等同於False的值,比如說Null 字元串或者空列表。
python中的none