在 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 所说,你不能这样做.在后一个示例中,您可能会遇到 None 是 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'