gpt4 book ai didi

python - 如何将两个或三个参数传递给一个函数?

转载 作者:太空宇宙 更新时间:2023-11-03 15:50:26 25 4
gpt4 key购买 nike

这可能与传统的 *args **kwargs 范式略有不同:

我有一个将三个独立参数作为输入的数学函数,但是,它也可以通过指定三个参数中的任意两个来求解(非紧凑地)。

目前,我有严格基于 a 和 b 的非紧凑型解决方案,其中 c 作为可选约束:

def func(a,b,c=None):
if c is not None:
# do something with a, b, and c
else:
# do something with only a, b
return result

但是,我希望能够指定 a、b 或 c 中的任意两个,并且仍然保留指定所有三个的选项。最符合 Pythonic 的方法是什么?

最佳答案

您可以只给它们所有默认值 None,然后将参数作为关键字参数传递:

def foo(a=None, b=None, c=None):
print(a, b, c)

foo(a=123, b=456)
foo(a=123, c=789)
foo(b=456, c=789)

这个例子产生:

123 456 None
123 None 789
None 456 789

关于python - 如何将两个或三个参数传递给一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47190911/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com