Python中省略对象有什么用

本篇文章为大家展示了Python中Ellipsis对象有什么用,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

什么是Ellipsis

在 Python 中你可能有时候会看到一个奇怪的用法,就像是这样:

> ...  Ellipsis

在你输入了三个点之后,Python 解释器非但不会报错,反而还会返回给你「Ellipsis」这么一个信息。那么这个有趣的东西是什么呢?

查阅 Python 官方文档后可以看到,它是一个**「内置常量」**(Built-in Constant)。经常用于对用户自定义的容器数据类型进行切片用法的扩展。

这也就意味着它可能是会作为一个「小众且另类」的语法糖来使用,但如果你用于 Python 中的容器数据类型(比如列表)进行切片索引时,可能会引发错误:

> nums = list(range(10))  >> nums  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]  >> nums[...]  Traceback (most recent call last):    File "", line 1, in   TypeError: list indices must be integers or slices, not ellipsis

除此之外,如果你使用的是 Python 2 的解释器,那么压根就不支持 Ellipsis 的用法,从一开始输入时就报错:

$ python2  WARNING: Python 2.7 is not recommended.   This version is included in macOS for compatibility with legacy software.   Future versions of macOS will not include Python 2.7.   Instead, it is recommended that you transition to using 'python3' from within Terminal.  Python 2.7.16 (default, Nov  9 2019, 05:55:08)   [GCC 4.2.1 Compatible Apple LLVM 11.0.0 (clang-1100.0.32.4) (-macos10.15-objc-s on darwin  Type "help", "copyright", "credits" or "license" for more information.  >> ...    File "", line 1      ...      ^  SyntaxError: invalid syntax

虽然说在列表中使用 Ellipsis 会报错,但是碰到这种情况你会发现解释器返回给你的是这样的东西:

> nums = [1,2,3]  >> nums  [1, 2, 3]  >> nums[1] = nums  >> nums  [1, [...], 3]

可以看到,这里我们将 nums 中的第二个元素替换成自身,就会形成不断地递归嵌套赋值,而解释器最后直接给出了头尾两个元素之外,其他全部元素都会被 ... null

Python中省略对象有什么用