Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
134 views
in Technique[技术] by (71.8m points)

python - the strange arguments of 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

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...