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将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
