Python中None与null的区别

Python中None与null的区别


一、Python 只有 None,没有 null

在 Python 中写 null 会直接报错:

python 复制代码
x = null      # NameError: name 'null' is not defined

正确写法是:

python 复制代码
x = None
print(x)          # None
print(type(x))    # <class 'NoneType'>

None 是 Python 的一个内置常量 ,类型是 NoneType。它表示"什么都没有""空值""未赋值"。


二、和其他语言的对照

语言 空值关键字 说明
Python None 唯一,首字母大写
C / C++ NULL / nullptr 空指针
Java null 引用类型默认值
JavaScript null 和 undefined 两个不同的空值
SQL NULL 数据库里的空值
JSON null 全小写
Go nil 空指针/空接口
Ruby nil 类似 Python 的 None

所以:

  • Java/JS/C 的 null → 对应 Python 的 None
  • Go/Ruby 的 nil → 也对应 Python 的 None
  • JSON 的 null → 转成 Python 后变成 None

三、None 的常见用法

1. 表示"没有值"

python 复制代码
result = None
if result is None:
    print("还没有结果")

2. 函数没有返回值时,默认返回 None

python 复制代码
def f():
    print("hi")

x = f()      # 打印 hi
print(x)     # None

3. 作为可选参数的默认值

python 复制代码
def greet(name=None):
    if name is None:
        print("你好,陌生人")
    else:
        print(f"你好,{name}")

greet()          # 你好,陌生人
greet("小明")     # 你好,小明

4. 字典的 get() 找不到键时返回 None

python 复制代码
d = {"a": 1}
print(d.get("b"))        # None
print(d.get("b", 0))     # 0,可以指定默认值

5. 类型标注里表示"可空"

python 复制代码
def f(x: int | None) -> str | None:
    ...

四、判断 None 要用 is,不要用 ==

这是 Python 的官方推荐写法:

python 复制代码
x = None

# 推荐
if x is None:
    ...

# 不推荐(虽然通常也能工作)
if x == None:
    ...

原因:

  • None 是单例 ,整个 Python 进程里只有一个 None 对象,所以用 is(身份比较)最准确、最快。
  • == 可能被自定义的 __eq__ 方法干扰,导致意外结果。
  • PEP 8 明确规定:与 None 比较用 is 或 is not。
python 复制代码
if x is not None:
    print("x 有值")

五、None 的"假值"特性

None 在布尔上下文里是 False:

python 复制代码
if None:
    print("不会执行")
else:
    print("None 是假值")   # 会执行

print(bool(None))          # False

常见的假值还有:0、0.0、""、[]、{}、()、set()、False。

所以下面两种写法在"只关心有没有值"时效果一样:

python 复制代码
if x:            # x 是 None、0、""、[] 等都会进 else
    ...

if x is not None:  # 只有 x 真的是 None 才进 else
    ...

区别很重要 :如果 x = 0,if x 为假,但 x is not None 为真。要根据业务语义选择。


六、None 不能做运算

python 复制代码
None + 1        # TypeError
None * 2        # TypeError
len(None)       # TypeError
None[0]         # TypeError

任何对 None 做运算或下标访问都会报 TypeError。所以拿到可能为 None 的值时,要先判断:

python 复制代码
x = d.get("key")
if x is not None:
    print(x + 1)

七、None 和 JSON 的转换

Python 的 None 转成 JSON 会变成 null:

python 复制代码
import json

data = {"name": "小明", "age": None}
json_str = json.dumps(data)
print(json_str)          # {"name": "\u5c0f\u660e", "age": null}

# 反过来
parsed = json.loads('{"age": null}')
print(parsed["age"])     # None

注意:

  • json.dumps 把 None 写成 null
  • json.loads 把 null 读成 None

八、常见坑

1. 把 None 当成 0 或空字符串用

python 复制代码
x = None
print(x + 1)      # TypeError,不是 0

2. 用 == 判断 None

python 复制代码
if x == None:     # 能跑,但不规范

3. 函数忘了 return,结果拿到 None

python 复制代码
def add(a, b):
    a + b          # 忘了 return

print(add(1, 2))   # None,不是 3

4. 列表排序时混入 None 会报错

python 复制代码
sorted([3, None, 1])   # TypeError: '<' not supported between 'NoneType' and 'int'

九、一句话总结

问题 答案
Python 有 null 吗? 没有 ,写 null 报 NameError
用什么表示空? None,首字母大写
None 是什么类型? NoneType,全局唯一单例
怎么判断? 用 is None / is not None,不要用 ==
布尔值? False
和 JSON 的关系? None ↔ null 互相转换

记住:Python 里只有 None,没有 null。判断它用 is,别用 ==。

相关推荐
wflynn12 小时前
GitHub 日榜趋势速报 | 2026-10-10
开源·github
fthux13 小时前
开源小工具 Who Arrives:看看你的公网 IP、地区、时区和网络
http·开源·github
来自于狂人13 小时前
GitHub 开源趋势日报 | 2026年10月10日,告别 Mermaid 的图表设计系统
开源·github
u13013014 小时前
GitHub 热榜项目:日榜(2026-10-10)
人工智能·github
Python测试之道15 小时前
GitHub 实战课|Playwright MCP:让 AI 真的会用浏览器
人工智能·github
小陈运维16 小时前
GitHub Actions + Docker + ACR + GHCR 自动化构建与发布
github
miofly17 小时前
AI 智能体用 83% 字节精确匹配反编译完整游戏
开源·github
TunerT_TQ19 小时前
开源评测】openai/math 深度拆解:722 份 AI 数学手稿与 Lean 形式化的工程真相
github
W.A委员会19 小时前
PID自动整定与LLM调优项目使用说明(源码附文末)
自动化·github