gpt4 book ai didi

python - python中根据参数类型选择函数

转载 作者:行者123 更新时间:2023-11-28 21:28:55 25 4
gpt4 key购买 nike

我有一个函数接受任意一组参数,然后根据参数的类型选择正确的函数来处理它们。

我目前的方法是在所有处理函数上使用一个装饰器来检查参数的类型,然后遍历所有函数直到一个函数接受参数。

这对我来说似乎有点老套,作为一个相对较新的 python 程序员,我想知道是否有更“pythonic”的方法来做到这一点。

所以,目前,我有这样的东西:

def function_router(*args):
for func in functions: #functions is a list of functions
try:
return func(*args)
except TypeError:
pass
#probably raise an exception if no function works

'functions' 中的每个函数都会有一个像这样的装饰器:

def accepts(*types) :
def my_decorator(func):
def wrapped(*args, **kwargs):
for i in range(len(types)):
if not isinstance(args[i], types[i]):
raise TypeError('Type error, %s not instance of %s, it is %s' %(args[i],types[i], type(args[i])))
return func(*args, **kwargs)
return wrapped
return my_decorator

编辑:天哪,我真的很喜欢阅读所有的解决方案。我选择的答案对我目前正在做的事情来说是最有效的,但我从所有答案中学到了一些东西,所以感谢大家抽出时间。

最佳答案

也许正确的方法是使用关键字参数,而不是依赖于参数的类型。这样,您就不必修饰小函数,只需正确命名参数即可。它还可以让您利用 Python 的鸭子类型。

关于python - python中根据参数类型选择函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6847189/

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