内置范围函数如何接受一个或三个参数?

2022-01-21 00:00:00 python function arguments range

问题描述

范围函数如何接受:单个参数,range(stop),或 range(start, stop),或 range(start,停止,步骤).它是否使用像 *arg 这样的 variadic 参数来收集参数,然后使用一系列 if 语句根据提供的参数数量分配正确的值?本质上,range() 是否指定如果有一个参数,则设置为停止参数,或者如果有两个,则它们是 startstop,或者如果有 3 个则分别设置为 stopstartstep?我想知道如果要在纯 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.

相关文章