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,别用 ==。

相关推荐
杨凯凡11 小时前
IT日报|2026-11-20:欧盟 AI 网络攻击、Valkey 9.2、GitHub 企业迁移
人工智能·github
TunerT_TQ12 小时前
Terraform OCI Provider 2026:工具链的骨架清晰可见,CRUD 的肌肉必须由你亲自验证
github
prince_zxill12 小时前
把 17 个散文件装进一个文件夹:拆解 claude-plugins-official 的插件打包术(47,413 Star 实测)
python·github·agent·mcp·claude code
wflynn13 小时前
GitHub 日榜趋势速报 | 2026-11-20
开源·github
TunerT_TQ15 小时前
【开源评测】google-labs-code/stitch-skills:从设计交接到可检查的组件产物
github
一条Go16 小时前
探测规则:为什么它是告警规则的一种,而不是独立的任务体系
后端·架构·github
一条Go17 小时前
开源新生代雷达 · 第 17 期
github
怕浪猫17 小时前
2026 GitHub 最火的 10 个视频制作与剪辑开源项目:AI 出片、代码生视频、无损剪辑怎么选(附实测截图)
github
dong_junshuai1 天前
每天一个开源项目#162 NGINX:流式响应背后的缓冲、背压与重试
github
测试员周周1 天前
【agent评测】:真实系统演示工具调用长什么样,用例怎么设计,怎么测
前端·后端·github