How can the built-in range function take a single argument or three?

前端 未结 4 1819
借酒劲吻你
借酒劲吻你 2020-12-06 05:44

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

4条回答
  •  天涯浪人
    2020-12-06 06:08

    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.

    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.

    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.

提交回复
热议问题