当前位置: 首页 > article >正文

Python中的null是什么?

Python中的null是什么?

在知乎上遇到一个问题,说:计算机中的「null」怎么读?

null正确的发音是/n^l/,有点类似四声‘纳儿’,在计算机中null是一种类型,代表空字符,没有与任何一个值绑定并且存储空间也没有存储值。

Python中其实没有null这个词,取而代之的是None对象,即特殊类型NoneType,代表空、没有。

None不能理解为0,因为0是有意义的,而None是一个特殊的空值。

>>> NoneType
NameError: name 'NoneType' is not defined
>>> type(None)
NoneType

None也不能理解为空字符'',因为空字符的类型是字符串。

>>>type('')
<class ''str'>

虽然表示空,但None是一个具体的Python对象,这和null含义不一样。

在Python中返回None:

>>> def has_no_return():
...     pass
>>> has_no_return()
>>> print(has_no_return())
None

你可以使用 Python 的标识函数id()检查 None 的唯一性,它返回某一对象的唯一标识符,如果两个变量的 id 相同,那么它们实际上指向的是同一个对象。

>>> NoneType = type(None)
>>> id(None)
10748000
>>> my_none = NoneType()
>>> id(my_none)
10748000
>>> another_none = NoneType()
>>> id(another_none)
10748000
>>> def function_that_does_nothing(): pass
>>> return_value = function_that_does_nothing()
>>> id(return_value)
10748000

在Python中,None的用处有很多,比如作为变量初始值、作为函数默认参数、作为空值等等。

变量初始值

>>> print(bar)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'bar' is not defined
>>> bar = None
>>> print(bar)
None

函数默认参数

def bad_function(new_elem, starter_list=[]):
    starter_list.append(new_elem)
    return starter_list

空值

>>> class DontAppend: pass
...
>>> def good_function(new_elem=DontAppend, starter_list=None):
...     if starter_list is None:
...         starter_list = []
...     if new_elem is not DontAppend:
...         starter_list.append(new_elem)
...     return starter_list
...
>>> good_function(starter_list=my_list)
['a', 'b', 'c', 'd', 'e']
>>> good_function(None, my_list)
['a', 'b', 'c', 'd', 'e', None]

总得来说,None是一个对象,而null是一个类型。

Python中沒有null,只有None,None有自己的特殊类型NoneType。

None不等于0、任何空字符串、False等。

在Python中,None、False、0、””(空字符串)、、()(空元組)、{}(空字典)都相当于False。


http://www.kler.cn/news/323220.html

相关文章:

  • 基于SpringBoot+Vue的小儿推拿培训管理系统
  • MySQL按照经纬度排序 查询出商家信息
  • Cisco ASA 9.22.1 发布下载,新增功能概览
  • Mysql—主从复制的slave添加及延迟回放
  • 2024年7月大众点评乌鲁木齐美食店铺基础信息
  • 物理学基础精解【26】
  • .NET MAUI(.NET Multi-platform App UI)上下文菜单
  • 【Redis入门到精通六】在Spring Boot中集成Redis(含配置和操作演示)
  • 机器学习查漏补缺(5)
  • 【刷题5】在排序数组中查找元素的第一个和最后一个位置
  • Android CCodec Codec2 (十五)C2DmaBufAllocator
  • 自动化办公-python中的open()函数
  • 深入理解 Nuxt.js 中的 app:error:cleared 钩子
  • 【hot100-java】【划分字母区间】
  • 消息中间件 Kafka 快速入门与实战
  • 让具身智能更快更强!华东师大上大提出TinyVLA:高效视觉-语言-动作模型,遥遥领先
  • mysql复合查询 -- 合并查询(union,union all)
  • 指令个人记录
  • Lab1:虚拟机kolla安装部署openstack,并创建实例
  • [大语言模型-论文精读] MoRAG - 基于多部分融合的检索增强型人体动作生成
  • 海尔嵌入式硬件校招面试题及参考答案
  • Python in Excel作图分析实战!
  • 关于Obj文件格式介绍与Unity加载Obj文件代码参考
  • 阿里云k8s发布vue项目
  • 防砸安全鞋这样挑,舒适又安心!
  • 用矩阵和统计报告估计polynomial线性回归的系数python
  • 直线模组降噪攻略
  • 【开源免费】基于SpringBoot+Vue.JS技术交流分享平台(JAVA毕业设计)
  • 16 Midjourney从零到商用·实战篇:产品工业设计
  • 2024AI做PPT软件如何重塑演示文稿的创作