Python None
None 是 Python 中表示「沒有值」或「空」的特殊常數,類似於其他語言中的 null 或 nil。
None 的用途
result = None
print(result) # None
print(type(result)) # <class 'NoneType'>
表示變數尚未有值
# 先宣告變數,稍後再賦值
user = None
# 經過某些處理後...
user = {"name": "Alice", "age": 25}
函數沒有回傳值
沒有 return 語句或 return 後面沒有值的函數,會回傳 None:
def greet(name):
print(f"Hello, {name}!")
result = greet("Alice") # 印出: Hello, Alice!
print(result) # None
def nothing():
return
print(nothing()) # None
表示查找失敗或無結果
def find_user(user_id):
users = {"1": "Alice", "2": "Bob"}
return users.get(user_id) # 找不到回傳 None
user = find_user("3")
if user is None:
print("User not found")
檢查是否為 None
使用 is 或 is not 來檢查是否為 None:
value = None
# 推薦用法
if value is None:
print("Value is None")
if value is not None:
print("Value is not None")
# 不推薦(雖然可以運作)
if value == None:
print("Value is None")
為什麼用
is 而不是 ==?因為 None 是一個單例物件 (singleton),Python 中只有一個 None 物件,使用 is 比較的是物件的身份(記憶體位置),更加明確且效率更高。None 在條件判斷中
None 是 Falsy 值,在條件判斷中會被當作 False:
value = None
if value:
print("Has value")
else:
print("No value") # 會執行這行
if not value:
print("Value is Falsy") # 會執行這行
但要注意,其他 Falsy 值(如 0、""、[])也會產生同樣的結果:
def process(data):
# 這樣寫無法區分 None 和空列表
if not data:
return "No data"
return f"Processing {data}"
print(process(None)) # No data
print(process([])) # No data(可能不是你想要的)
# 如果要明確檢查 None
def process_v2(data):
if data is None:
return "No data"
if not data:
return "Empty data"
return f"Processing {data}"
print(process_v2(None)) # No data
print(process_v2([])) # Empty data
None 作為預設參數
函數參數常用 None 作為預設值:
# 不好的做法 - 用可變物件作為預設值
def add_item_bad(item, items=[]):
items.append(item)
return items
# 每次呼叫會共用同一個 list!
print(add_item_bad(1)) # [1]
print(add_item_bad(2)) # [1, 2] - 意外!
# 好的做法 - 用 None 作為預設值
def add_item_good(item, items=None):
if items is None:
items = []
items.append(item)
return items
print(add_item_good(1)) # [1]
print(add_item_good(2)) # [2] - 正確!
None 和其他型別比較
None 只等於自己:
print(None == None) # True
print(None is None) # True
print(None == False) # False
print(None == 0) # False
print(None == "") # False
print(None == []) # False