Python range 函数如何在实际参数之前有一个默认参数?
我正在编写一个函数,它接受一个可选列表并将其扩展到指定的长度。我没有将其写为 foo(n, list=None) ,而是想知道如何模拟 Python 范围函数的行为,该函数的工作原理如下:
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(5, 10)
[5, 6, 7, 8, 9]
也就是说,首先使用默认参数。作为参考,尝试天真地设置它会返回语法错误:
def foo(x=10, y):
return x + y
SyntaxError: non-default argument follows default argument
所以我想知道,这是硬编码到范围内的吗?或者可以效仿这种行为吗?
I'm writing a function that takes an optional list and extends it to the length specified. Rather than writing it as foo(n, list=None)
I was wondering how I might emulate the behavior of Python's range function which works like:
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(5, 10)
[5, 6, 7, 8, 9]
That is, with the default parameter first. For reference trying to naively set this up returns a syntax error:
def foo(x=10, y):
return x + y
SyntaxError: non-default argument follows default argument
So I'm wondering, is this hard-coded into range? Or can this behavior be emulated?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
其他人已经展示了如何使用参数计数来完成此操作。不过,如果我自己用 Python 实现它,我会更像这样。
Others have shown how it can be done using argument counting. If I were to implement it myself in Python, though, I'd do it more like this.
它们不是真正的关键字参数。
如果有一个参数,那就是极限。
如果有两个参数,第一个是起始值,第二个是限制。
如果有三个参数,第一个是起始值,第二个是限制,第三个是步幅。
They aren't real keyword arguments.
If there's one argument, it's the limit.
If there are two arguments, the first is the start value and the second is the limit.
If there are three arguments, the first is the start value, the second is the limit, and the third is the stride.
在纯Python中编写
range
的一种方法是One way to write
range
in pure python would bePython 通过查看参数的数量来实现
range()
。 编写此代码的 Python 版本应该不会太难:从 rangeobject.c
Python implements
range()
by looking at the number of arguments. It shouldn't be too hard to write a Python version of this codefrom rangeobject.c:
考虑:
Consider: