Python 中的空物件


Python 沒有空物件。但最接近的類似物件是 None。在本文中,我們將瞭解 None 在 Python 中的行為。

檢查空值和 None 的型別,我們發現沒有 Null 型別,而 None 物件的型別是 NoneType。

示例

print(type(None))
print(type(Null))

輸出

執行以上程式碼,我們將得到以下結果:

Traceback (most recent call last):
   File "C:\Users\xxx\scratch.py", line 4, in
      print(type(Null))
NameError: name 'Null' is not defined

關於 None 的關鍵事實

  • None 等同於 False。

  • None 等同於 False。

  • None 等同於 False。

  • None 是一個空字串。

  • None 等於 0。

  • 將 None 與任何東西進行比較始終會返回 False,除了 None 本身。

Python 中的空變數

未定義的變數與空變數不同。如果將 None 分配給 Python 中的變數,則該變數將為空。

示例

var_a = None
print('var_a is: ',var_a)
print(var_b)

輸出

執行以上程式碼,我們將得到以下結果:

Traceback (most recent call last):
   File "C:\Users\Pradeep\AppData\Roaming\JetBrains\PyCharmCE2020.3\scratches\scratch.py", line 5, in <module>
      print(var_b)
NameError: name 'var_b' is not defined
var_a is: None

None 不與方法關聯

如果某個變數被宣告為 None,則不能使用任何方法向其新增或刪除元素。

示例

 線上演示

listA = [5,9,3,7]
listA.append(18)
print(listA)
listA = None
listA.append(34)
print(listA)

輸出

執行以上程式碼,我們將得到以下結果:

[5, 9, 3, 7, 18]
Traceback (most recent call last):
   File "C:\Users\Pradeep\AppData\Roaming\JetBrains\PyCharmCE2020.3\scratches\scratch.py", line 7, in
      listA.append(34)
AttributeError: 'NoneType' object has no attribute 'append'

更新於: 2021年1月25日

2K+ 次瀏覽

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.