python里None 表示False嗎? (我是新手)

state = states.get(texas, None)

if not state

print 「sorry, no texas.」

.get()返回的是None嗎?然後if not state就相當於if not None嗎?


這個其實在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

所以回到問題,not None的確會返回True。不過一定要警惕的是,if a is None和if a,if a is not None和if not a不可以隨便混用,前面也說過了,它們在很多時候是不同的,比如說當a是一個列表的時候if not a其實是判斷a為None或者為空。

所以準確來說,你的這句

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的值,比如說空字元串或者空列表。


&>&>&> not 1
False
&>&>&> not False
True
&>&>&> not True
False
&>&>&> not None
True


None和False它們的主要區別是在語義上:False和True對應,它作為布爾類型用來描述邏輯中「假」這個概念;None和「存在元素」相對應,「存在元素」反過來為「不存在元素」,也就是None。這兩個對象在實際使用中也應該遵守這個規則。

比如在題主中給出的例子,get方法用來獲取Dict中的某個元素,當「不存在該元素」的時候就應該返回一個None。而其他一些用於判斷真假、是否符合某個規則的方法就應該返回True或者False。比如isalpha方法用於判斷一個字元串中是否只含有英文單詞,它的返回值就只有True和False。


Python中有一種NoneType的對象類型,None是這個類型的唯一值。False是bool類型的值。在python中,每一個對象均有一個bool值。像空字元串、空列表、空字典這些對象的bool值就是False,如下圖:

也就是說,None是一個對象,其類型為NoneType,作為一個對象其bool值為False。這樣應該清楚了吧?第一個認真回答的問題,希望別出什麼錯誤啊,誠惶誠恐。


推薦閱讀:

請教在這段語句中li = [lambda :x for x in range(10)]的步驟是怎樣的?
如何將python list中每12項的平均值組成一個新的list?
python和C#結合的效果如何?是否能讓C#寫的程序調用python的庫?
自學python遇到如下問題如何解決?(主要有關模塊安裝的問題)
Python 用 * (重複運算符) 和迭代器生成 list 有何不同?

TAG:Python | Python入門 |