我需要编写一个接受 3 个参数的方法:
- a
string
带有函数名称
- 一个有序的
list
该函数的参数。这包括具有默认值的参数和*varargs
,但不包括**kwargs
- a
dict
表示任何附加关键字参数,或None
如果没有
我需要使用此输入来检索函数并调用它。例如:
def dispatch(name, args, kwargs=None):
do_magic_here(name, args, kwargs)
def meth1():
print "meth1"
def meth2(a, b):
print "meth2: %s %s" % (a, b)
def meth3(a, **kwargs):
print "meth3: " + a
for k,v in kwargs.iteritems():
print "%s: %s" % (k,v)
我需要能够调用这样的东西:
>>> dispatch("meth1", [])
meth1
>>> dispatch("meth2", [1, 3])
meth2: 1 3
>>> dispatch("meth3", [1], {"hello":2, "there":3})
meth3: 1
hello: 2
there: 3
我可以这样做:
def do_magic_here(name, args, kwargs=None):
if name=="meth1":
meth1()
if name=="meth2":
meth2(args[0], args[1])
if name=="meth3":
meth3(args[0], **kwargs)
但我正在尝试分派 40 个方法,而且这个数字可能会增加,所以我希望有一种更加编程化的方法来做到这一点。我正在看一些东西getattr
,但我不太明白。