简体   繁体   English

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

[英]Choosing a function based on parameter types in python

I have a function that is taking an arbitrary set of arguments and then choosing the correct function to process them based on the types of the arguments. 我有一个函数,它接受任意一组参数,然后根据参数的类型选择正确的函数来处理它们。

My current approach is using a decorator on all of the processing functions that checks the types of the arguments, and then iterating through all of the functions until one accepts the arguments. 我当前的方法是在所有处理函数上使用装饰器,以检查参数的类型,然后迭代所有功能,直到一个函数接受参数为止。

Something about this seems a little hacky to me, and as a relatively new python programmer, I was wondering if there was a more 'pythonic' method to doing this. 对我来说,这似乎有些棘手,作为一个相对较新的python程序员,我想知道是否还有一种更“ pythonic”的方法可以做到这一点。

so, currently, I have something like this: 所以,目前,我有这样的事情:

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

and each function in 'functions' would have a decorator like this: 并且“功能”中的每个功能都会有一个这样的装饰器:

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

EDIT: Oh man, I actually really liked reading all of the solutions. 编辑:哦,老兄,我实际上真的很喜欢阅读所有解决方案。 The answer I chose was most effective for what I'm currently doing, but I learned something from all of the answers, so thank you all for your time. 我选择的答案对于当前正在执行的操作最为有效,但是我从所有答案中都学到了一些东西,因此感谢您的宝贵时间。

Perhaps the right way to do this is to use keyword arguments, instead of relying on the types of the arguments. 也许正确的方法是使用关键字参数,而不是依赖参数的类型。 That way, you don't have to decorate the little functions, just name the arguments correctly. 这样,您不必修饰小功能,只需正确命名参数即可。 It will also let you take advantage of Python's duck typing. 它还将使您能够利用Python的鸭子类型。

听起来您好像要描述多重方法,为此GvR 以装饰器的形式提供了一个不错的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM