Python使用getattr调用带可变参数的函数 [英] Python using getattr to call function with variable parameters

查看:42
本文介绍了Python使用getattr调用带可变参数的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 getattr 根据变量调用不同的函数.

I'm using getattr to call different functions depending on a variable.

我正在做这样的事情:

getattr(foo, bar) ()

那行得通,调用 foo.bar() 之类的函数

That works, calling functions like foo.bar()

我的问题是我有bar"函数,我想用不同的参数调用它.例如:

My problem is that I have 'bar' functions and I want to call it with different parameters. For example:

def f1() :
  pass

def f2(param1) :
  pass

def f3(param1,param2) :
  pass

所以 'bar' 可以是 f1、f2 或 f3

so 'bar' could be f1, f2, or f3

我试过这个:假设 params 是一个列表,其中包含 'bar' 函数所需的所有参数

I tried this: assumming that params is a list which contains all parameters needed for the 'bar' function

getattr(foo, bar) (for p in params :)

我正在寻找一个干净"的解决方案,不需要观察 params 变量的长度

I watching for a "clean" solution, with no needed to watch the length on the params variable

推荐答案

您可以尝试以下操作:

getattr(foo, bar)(*params)

如果 params 是列表或元组,则此方法有效.params 中的元素将按顺序解包:

This works if params is a list or a tuple. The elements from params will be unpacked in order:

params=(1, 2)
foo(*params)

相当于:

params=(1, 2)
foo(params[0], params[1])

如果有关键字参数,你也可以这样做.

If there are keyword arguments, you can do that too.

getattr(foo, bar)(*params, **keyword_params)

其中 keyword_params 是字典.

此外,这个答案实际上与 getattr 无关.它适用于任何函数/方法.

Also, This answer is really independent of getattr. It will work for any function/method.

这篇关于Python使用getattr调用带可变参数的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆