在 Python 中,我可以根据其他参数指定函数参数的默认值吗? [英] In Python, can I specify a function argument's default in terms of other arguments?

查看:25
本文介绍了在 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 所说,你不能这样做.在后一个示例中,您可能会遇到 Nonearg2 的有效值的情况.如果是这种情况,您可以使用标记值:

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天全站免登陆