gpt4 book ai didi

python - 使 Python 3 函数接受预设的正确方法是什么?

转载 作者:行者123 更新时间:2023-11-28 20:39:39 24 4
gpt4 key购买 nike

考虑一个接受三个参数的函数:

def foo(arg1, arg2, arg3):
pass

和一个在元组中提供预设的类:

class Presets():
preset1 = (1, 2, 3)
preset2 = (3, 2, 1)

使函数接受三个单独参数或一个参数元组的正确方法是什么?

两者都应该是有效的函数调用:

foo(1,1,1)
foo(Presets.preset2)

最佳答案

一种方法是使用装饰器。

from functools import wraps

def tupled_arguments(f):
@wraps(f) # keeps name, docstring etc. of f
def accepts_tuple(tup, *args):
if not args: # only one argument given
return f(*tup)
return f(tup, *args)
return accepts_tuple

@tupled_arguments
def foo(arg1, arg2, arg3):
pass

现在可以通过单独传递所有参数或按顺序传递它们来调用函数。

foo(1,2,3)
foo((1,2,3))
foo([1,2,3])

都是平等的调用。

关于python - 使 Python 3 函数接受预设的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37517967/

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