在Python中,我可以指定一个函数参数在其他参数方面默认? [英] In Python, can I specify a function argument's default in terms of other arguments?

查看:146
本文介绍了在Python中,我可以指定一个函数参数在其他参数方面默认?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个Python函数有两个参数,但我想第二个参数是可选的,默认是无论是作为第一个参数传递。所以,我希望做这样的事情:

Suppose I have a python function that takes two arguments, but I want the second arg to be optional, with the default being whatever was passed as the first argument. So, I want to do something like this:

def myfunc(arg1, arg2=arg1):
    print (arg1, arg2)

除了将不起作用。我能想到的唯一的解决方法是这样的:

Except that doesn't work. The only workaround I can think of is this:

def myfunc(arg1, arg2=None):
    if arg2 is None:
        arg2 = arg1
    print (arg1, arg2)

有没有更好的方法来做到这一点?

Is there a better way to do this?

推荐答案

由于@Ignacio说,你不能做到这一点。在你后面的例子中,你可能会遇到这样的情况 ARG2 的有效值。如果是这样的话,你可以使用一个哨兵值:

As @Ignacio says, you can't do this. In your latter example, you might have a situation where None is a valid value for arg2. If this is the case, you can use a sentinel value:

sentinel = object()
def myfunc(arg1, arg2=sentinel):
    if arg2 is sentinel:
        arg2 = arg1
    print (arg1, arg2)

myfunc("foo")           # Prints 'foo foo'
myfunc("foo", None)     # Prints 'foo None'

这篇关于在Python中,我可以指定一个函数参数在其他参数方面默认?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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