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

前端 未结 4 1816
借酒劲吻你
借酒劲吻你 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 05:58

    lqc's answer demonstrates how range is implemented in C. You may still be curious about how range would be implemented if Python's built in functions were written in Python. We can read PyPy's source code to find out. From pypy/module/__builtin__/functional.py:

    def range_int(space, w_x, w_y=NoneNotWrapped, w_step=1):
        """Return a list of integers in arithmetic position from start (defaults
    to zero) to stop - 1 by step (defaults to 1).  Use a negative step to
    get a list in decending order."""
    
        if w_y is None:
            w_start = space.wrap(0)
            w_stop = w_x
        else:
            w_start = w_x
            w_stop = w_y
    

    The first argument, space, appears as an argument in all the built-in functions I saw, so I'm guessing it's kind of like self in that the user does not directly supply it. Of the remaining three arguments, two of them have default values; so you can call range with one, two, or three arguments. How each argument is interpreted depends upon how many arguments were supplied.

提交回复
热议问题