How can the built-in range function take a single argument or three?(内置范围函数如何接受一个或三个参数?)
问题描述
范围函数如何接受:单个参数,range(stop)
,或 range(start, stop)
,或 range(start,停止,步骤)
.它是否使用像 *arg
这样的 variadic
参数来收集参数,然后使用一系列 if 语句根据提供的参数数量分配正确的值?本质上,range()
是否指定如果有一个参数,则设置为停止参数,或者如果有两个,则它们是 start
和 stop
,或者如果有 3 个则分别设置为 stop
、start
和 step
?我想知道如果要在纯 CPython 中编写 range 会如何做到这一点.
How can the range function take either: a single argument, range(stop)
, or range(start, stop)
, or range(start, stop, step)
. Does it use a variadic
argument like *arg
to gather the arguments, and then use a series of if statements to assign the correct values depending on the number of arguments supplied? In essence, does range()
specify that if there is one argument, then it set as the stop argument, or if there are two then they are start
, and stop
, or if there are three then it sets those as stop
, start
, and step
respectively? I'd like to know how one would do this if one were to write range in pure CPython.
推荐答案
范围采用 1、2 或 3 个参数.这可以通过 def range(*args)
和显式代码来实现,以在获得 0 个或超过 3 个参数时引发异常.
Range takes, 1, 2, or 3 arguments. This could be implemented with def range(*args)
, and explicit code to raise an exception when it gets 0 or more than 3 arguments.
它不能用默认参数来实现,因为你不能在默认值之后有一个非默认值,例如def range(start=0, stop, step=1)
.这本质上是因为 python 必须弄清楚每个调用的含义,所以如果你用两个参数调用,python 需要一些规则来确定你覆盖了哪个默认参数.没有这样的规则,根本不允许.
It couldn't be implemented with default arguments because you can't have a non-default after a default, e.g. def range(start=0, stop, step=1)
. This is essentially because python has to figure out what each call means, so if you were to call with two arguments, python would need some rule to figure out which default argument you were overriding. Instead of having such a rule, it's simply not allowed.
如果您确实想使用默认参数,您可以执行以下操作:def range(start=0, stop=object(), step=1)
并明确检查停止
.
If you did want to use default arguments you could do something like: def range(start=0, stop=object(), step=1)
and have an explicit check on the type of stop
.
这篇关于内置范围函数如何接受一个或三个参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:内置范围函数如何接受一个或三个参数?


基础教程推荐
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 筛选NumPy数组 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01