Python中的null是什么?

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

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

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

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

Python 复制代码
>>> NoneType
NameError: name 'NoneType' is not defined
>>> type(None)
NoneType

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

python 复制代码
>>>type('')
<class ''str'>

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

在Python中返回None:

python 复制代码
>>> def has_no_return():
...     pass
>>> has_no_return()
>>> print(has_no_return())
None

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

Python 复制代码
>>> 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的用处有很多,比如作为变量初始值、作为函数默认参数、作为空值等等。

变量初始值

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

函数默认参数

python 复制代码
def bad_function(new_elem, starter_list=[]):
    starter_list.append(new_elem)
    return starter_list

空值

python 复制代码
>>> 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。

相关推荐
精灵vector几秒前
构建专家级SQL Agent交互
python·aigc·ai编程
旷世奇才李先生5 分钟前
Lua 安装使用教程
开发语言·lua
阿幸软件杂货间15 分钟前
Windows 10 2016 长期服务版
windows·系统·win10
Vertira18 分钟前
pdf 合并 python实现(已解决)
前端·python·pdf
不良手残22 分钟前
IDEA类和方法注释模板设置-保姆教程
java·开发语言
太凉22 分钟前
Python之 sorted() 函数的基本语法
python
项目題供诗39 分钟前
黑马python(二十四)
开发语言·python
就改了1 小时前
JUC小册——公平锁和非公平锁
java·开发语言
晓13131 小时前
OpenCV篇——项目(二)OCR文档扫描
人工智能·python·opencv·pycharm·ocr
是小王同学啊~1 小时前
(LangChain)RAG系统链路向量检索器之Retrievers(五)
python·算法·langchain