内置的功能范围如何能带一个参数或三个? [英] How can the built-in range function take a single argument or three?

查看:155
本文介绍了内置的功能范围如何能带一个参数或三个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道,如果有人可以告诉我,该范围内的功能如何利用两种:一个参数,范围(停止)范围(启动,停止)范围(启动,停止,步)。是否使用像可变参数参数 * ARG 来收集参数,然后用一系列的if语句分配正确的值取决于参数的数量提供?从本质上讲,确实范围()规定,如果有一个参数,然后将其设置为停止参数,或者如果有两个那么他们是启动停止,或者如果有三个,然后它会将这些作为停止启动分别?我想知道怎么一会做,如果一个人在纯CPython的写范围。谢谢!

I would like to know, if anyone can tell me, how the range function can 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. Thanks!!!

更新
我没有澄清,当我最初问这个问题,我想知道在CPython的答案。无论感谢您对您所有的回应!我发现他们都非常有启发性。这是什么样的反馈,让我的爱计算器,以及使人们特别之处!

Update: I did not clarify, when I initially asked the question, that I wanted to know the answer in Cpython. Regardless thank you for all of your responses! I found them all fairly enlightening. This is the kind of feedback that makes me love stackoverflow and the people that make it so special!

推荐答案

范围需要,1,2,或3个参数。这可以用实现高清范围(*参数),并明确code引发异常时,得到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范围(启动= 0,停止步= 1)。这主要是因为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范围(启动= 0,停止=对象(),步= 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.

这篇关于内置的功能范围如何能带一个参数或三个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆