范围的奇怪论点 [英] the strange arguments of range

查看:108
本文介绍了范围的奇怪论点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

python3中的range函数带有三个参数.其中两个是可选的.因此参数列表如下所示:

The range function in python3 takes three arguments. Two of them are optional. So the argument list looks like:

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

[start], stop, [step]

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

This means (correct me if i'm wrong) there is an optional argument before a non-optional argument. But if i try to define a function like this i get this:

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

这是我作为普通" python用户不能做的事情吗,还是可以某种方式定义这样的功能?当然我可以做类似的事情

Is this something I can't do as a 'normal' python user or can i somehow define such a function? Of course i could do something like

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

但是例如,帮助功能将显示奇怪的信息.所以我真的很想知道是否有可能定义一个像内置range这样的函数.

but for example the help function would then show strange informations. So i really want to know if it's possible do define a function like the built-in range.

推荐答案

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

range() takes 1 positional argument and two optional arguments, and interprets these arguments differently depending on how many arguments you passed in.

如果仅传入了一个参数,则将其假定为stop参数,否则将第一个参数解释为开始.

If only one argument was passed in, it is assumed to be the stop argument, otherwise that first argument is interpreted as the start instead.

实际上,range()用C编码,采用可变数量的参数.您可以像这样模拟:

In reality, range(), coded in C, takes a variable number of arguments. You could emulate that like this:

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

但是您也可以交换参数:

but you could also just swap arguments:

def range(start, stop=None, step=1):
    if stop is None:
        start, stop = 0, start

这篇关于范围的奇怪论点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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