3

经过多年的 Java、C、c++ 等,我刚刚开始使用 python。我有一长串文件/模块,每个文件/模块都包含一个我想动态调用的主要方法。对于每个关键字,我都有一个名为 get_foo 的 .py 文件,在每个 get_foo.py 中,都有一个 foo 方法。所以我想传入命令名“foo”并执行get_foo.foo()方法

我真的不想用丑陋的 if/then/else 块来做这件事

sections = [ "abstract",  "claim",  "drawing", "examiner"]
command = "claim"

我想要什么

exec("get_" + command + "." + command)

但我真的不知道 exec/eval/etc 的哪些区域会这样做。

4

3 回答 3

5

使用importlib模块动态导入,并getattr()找到你的功能:

import importlib

def call_command(cmd):
    mod = importlib.import_module('get_' + cmd)
    func = getattr(mod, cmd)
    return func()

Or, simply import all your modules and add them to a dict to map command to callable:

import get_foo, get_bar, get_baz

commands = dict(foo=get_foo.foo, bar=get_bar.bar, baz=get_baz.baz)

def call_command(cmd):
    return commands[cmd]()
于 2012-12-19T20:39:09.753 回答
4

解决方案 1

from get_foo1 import foo1 # get_foo1.py in directory
from get_foo2 import foo2 # get_foo2.py in directory
foo1()
foo2()

也可以通过其他方式完成

import get_foo1
import get_foo2

get_foo1.foo1()
get_foo2_foo2()

动态地称呼他们你也有很多方法

commands = {"foo1":foo1, "foo2":foo2} 
# notice foo1 and foo2 have no "()" because we're referencing function and not calling it

#and then call them

commands["foo1"]()   # notice (), this means we're calling function now
于 2012-12-19T20:35:46.610 回答
3

You can have a function which calls a function from a module:

def call_function(func):
    module = __import__("get_" + func)
    return getattr(module, func)()

Then call this function like this:

call_function("claim")
于 2012-12-19T20:41:31.987 回答