Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/ant/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
根据python中的参数类型选择函数_Python - Fatal编程技术网

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

根据python中的参数类型选择函数,python,Python,我有一个函数,它接受一组任意的参数,然后根据参数的类型选择正确的函数来处理它们 我目前的方法是在所有处理函数上使用一个decorator来检查参数的类型,然后遍历所有函数,直到接受参数为止 这方面的一些内容对我来说似乎有点老套,作为一个相对较新的python程序员,我想知道是否有一种更“pythonic”的方法来实现这一点 所以,目前,我有这样的想法: def function_router(*args): for func in functions: #functions is a li

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

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

这方面的一些内容对我来说似乎有点老套,作为一个相对较新的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
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
“函数”中的每个函数都会有这样一个装饰器:

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
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的duck类型。

听起来您好像在试图描述多重方法,GvR为其提供了一个

您可以给出一些真实的示例,说明如何使用装饰器吗?澄清问题:您是说每个函数都使用kwargs,如果我调用一个kwargs错误的函数,它会抛出一个错误?(本质上,相同的逻辑,在没有装饰师的情况下完成了吗?)。使用
**kwargs