默认和非默认参数的顺序 [英] Order of default and non-default arguments

查看:72
本文介绍了默认和非默认参数的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中,我知道默认参数放在最后,非默认参数不能跟在默认参数之后.那样就好.例如:

<预><代码>>>>def foo(x=0, y):返回 x, y语法错误:非默认参数跟随默认参数

这符合预期.

但是,如果我希望 第一个参数应该是默认参数怎么办?例如,从上面的代码可以明显看出,x 必须是第一个参数,并且它的默认值应该是 0.

可以这样做吗?我问是因为即使在 range 函数中,我猜它是这样的:

def range(start=0, end):经过

那么这是如何完成的,如果不可能,range 是如何实现的?请注意,我坚持将第一个参数设为默认值,这就是重点.我使用 range 作为示例,因为它非常适合我的问题.当然,可以将 range 实现为 def range(end, start=0),但这不是重点.

解决方案

嗯,range 是 C 代码,可以稍微好一点.无论如何,你可以这样做:

def range(start, stop=None):if stop is None: # 只有一个参数,将停止视为开始 ...停止 = 开始开始 = 0...

并相应地记录函数.

In Python, I understand that default arguments come at the end and that non-default arguments cannot follow a default argument. That is fine. Like for example:

>>> def foo(x=0, y):
        return x, y
SyntaxError: non-default argument follows default argument

That is OK as expected.

However, what about the case when I want that the first argument should be a default one? Like for example, as is apparent from the above code, x has to be the first argument and it should have a default value of 0.

Is it possible to do this? I am asking because even in the range function, I am guessing it is something like this:

def range(start=0, end):
    pass

So how is this done and if it is not possible, how is this implemented by range? Note that I am insisting on the first argument to be default, that is the entire point. I am using range as an example because it fits my problem perfectly. Of course one could implement range as def range(end, start=0), but that is not the point.

解决方案

Well, range is C code which can do this slightly better. Anyways, you can do this:

def range(start, stop=None):
    if stop is None: # only one arg, treat stop as start ...
        stop = start
        start = 0
    ...

and document the function accordingly.

这篇关于默认和非默认参数的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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