16

python3 中的 range 函数接受三个参数。其中两个是可选的。所以参数列表看起来像:

[开始],停止,[步骤]

这意味着(如果我错了,请纠正我)在非可选参数之前有一个可选参数。但是,如果我尝试定义这样的函数,我会得到:

>>> def foo(a = 1, b, c = 2):
    print(a, b, c)
SyntaxError: non-default argument follows default argument

这是我作为“普通”python用户无法做到的事情,还是我可以以某种方式定义这样的函数?当然我可以做类似的事情

def foo(a, b = None, c = 2):
    if not b:
        b = a
        a = 1

但例如帮助功能会显示奇怪的信息。所以我真的很想知道是否可以定义一个类似内置的函数range

4

4 回答 4

18

range()接受 1 个位置参数和两个可选参数,并根据传入的参数数量对这些参数进行不同的解释。

如果只传入一个参数,则假定它是stop参数,否则将第一个参数解释为开始。

实际上,range()C 编码的,接受可变数量的参数。你可以这样模拟:

def foo(*params):
    if 3 < len(params) < 1:
        raise ValueError('foo takes 1 - 3 arguments')
    elif len(params) == 1
        b = params[0]
    elif:
        a, b = params[:2]
    c = params[2] if len(params) > 2 else 1

但你也可以交换参数:

def range(start, stop=None, step=1):
    if stop is None:
        start, stop = 0, start
于 2013-04-08T09:05:26.043 回答
13

range不接受关键字参数:

range(start=0,stop=10)
TypeError: range() takes no keyword arguments

它需要 1、2 或 3 个位置参数,它们根据它们的数量进行评估:

range(stop)              # 1 argument
range(start, stop)       # 2 arguments
range(start, stop, step) # 3 arguments

即不可能创建一个具有定义stopstep默认值的范围start

于 2013-04-08T09:07:40.047 回答
1
def foo(first, second=None, third=1):
     if second is None:
         start, stop, step = 0, first, 1
     else:
         start, stop, step = first, second, third
于 2013-04-08T09:06:29.580 回答
0

正如您现在所知道的那样,真正的答案是这range是一个 C 函数,由于某种原因它没有与 python 相同的规则(很高兴知道为什么)。

People might hate me for suggesting this but I've being doing this for range since I have a terrible memory of what the order of things are. Imo this shouldn't be a problem so I'm fixing it:

range(*{'start':0,'stop':10,'step':2}.values())

the reason I made it a one liner is because I don't want to have to define a range function that needs to be defined everywhere or imported everywhere. This is pure python.

于 2020-06-12T18:51:22.033 回答