Python range函数在实际值之前如何具有默认参数? [英] How does the Python range function have a default parameter before the actual one?

查看:227
本文介绍了Python range函数在实际值之前如何具有默认参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在编写一个函数,该函数接受一个可选列表并将其扩展到指定的长度.而不是将其编写为foo(n,list = None),我想知道如何模拟Python的range函数的行为,其工作方式如下:

So 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?

推荐答案

它们不是真正的关键字参数.

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函数在实际值之前如何具有默认参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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