如何处理有时未使用的函数参数?
How to deal with sometimes unused arguments of function?
你能告诉我如何处理有时未使用的函数参数吗?提前致谢!
函数:
def foo(a, b=2, c="default"):
print(c)
return a + b
用法:
arg_1 = int(input())
if arg_1 == 2:
arg_2 = 3
arg_3 = "using 3"
else:
# what can I do here?
arg_2 = *universal_value_that_is_disabling_argument
arg_3 = *universal_value_that_is_disabling_argument
# I know that I can use arg_2 = 2 and arg_3 = "default",
# but it is not really convenient when there are many arguments
foo(arg_1, b=arg_2, c=arg_3)
我知道我可以做这样的事情,但是当参数很多时不太方便:
arg_1 = int(input())
if arg_1 == 2:
foo(arg_1, 3, "using 3")
else:
foo(arg_1)
通过解包命名参数的字典来调用它。然后你可以简单地省略应该获得默认值的参数。
if arg_1 == 2:
options = {'b': 3, 'c': 'using 3'}
else:
options = {}
foo(arg_1, **options)
你能告诉我如何处理有时未使用的函数参数吗?提前致谢!
函数:
def foo(a, b=2, c="default"):
print(c)
return a + b
用法:
arg_1 = int(input())
if arg_1 == 2:
arg_2 = 3
arg_3 = "using 3"
else:
# what can I do here?
arg_2 = *universal_value_that_is_disabling_argument
arg_3 = *universal_value_that_is_disabling_argument
# I know that I can use arg_2 = 2 and arg_3 = "default",
# but it is not really convenient when there are many arguments
foo(arg_1, b=arg_2, c=arg_3)
我知道我可以做这样的事情,但是当参数很多时不太方便:
arg_1 = int(input())
if arg_1 == 2:
foo(arg_1, 3, "using 3")
else:
foo(arg_1)
通过解包命名参数的字典来调用它。然后你可以简单地省略应该获得默认值的参数。
if arg_1 == 2:
options = {'b': 3, 'c': 'using 3'}
else:
options = {}
foo(arg_1, **options)