如何在 Python Dispatch Table 中传递参数

How to pass parameters in a Python Dispatch Table

我正在尝试通过以下方式构建调度:

def run_nn(type=None):
    print type, 'nn'
    return

def run_svm(type=None):
    print type, 'svm'
    return


action = {'nn' : run_nn( type=None),
          'svm' : run_svm(type=None),}

我希望函数 仅在 被调用时执行,例如:

 action.get('nn',type='foo')

期望它打印:

foo nn

但它打破了给予:

TypeError: get() takes no keyword arguments

正确的做法是什么?

此外,两个函数run_nn()run_svm()甚至没有被调用就被执行了。我不想要那个。我怎样才能避免它?

您在构建词典时正在调用函数。您应该将函数对象放在字典中而不调用它们。然后,get 来自字典的适当函数并使用关键字参数调用它。

你想要的是:

action = {'nn' : run_nn,
          'svm' : run_svm,}
...
action.get('nn')(type='foo') # get function object from dict and then call it.

我建议您使用 action['nn'] 而不是 action.get('nn'),因为您没有在 get 方法中指定任何默认的 callableget 方法 returns None 当你没有指定时。 KeyErrorTypeError 直观得多 NoneType 对象在这种情况下不可调用

另一方面,您可以删除那些 return 语句,因为您实际上并没有 returning 任何东西。如果没有它们,你的函数仍然会 return

顺便说一句,我觉得你的函数想要根据 type 改变行为(尽管你的 type 是违反直觉的,因为它总是一个字符串)。在任何情况下,您都可以查看 functools.singledispatch. That'll transform your function(s) into a single-dispatch generic function 以及创建多个重载实现的可能性。

最后,尽管 type 确实是一个很好的参数名称,但是当您需要在函数中使用内置 type 时,您会 运行 遇到问题。