使用字典选择要执行的功能 [英] Using a dictionary to select function to execute

查看:197
本文介绍了使用字典选择要执行的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用函数式编程来创建一个包含一个键和一个函数来执行的字典:

I am trying to use functional programming to create a dictionary containing a key and a function to execute:

myDict={}
myItems=("P1","P2","P3",...."Pn")
def myMain(key):
    def ExecP1():
        pass
    def ExecP2():
        pass
    def ExecP3():
        pass
        ...
    def ExecPn():
        pass  

现在,我看到一个代码用于在模块中找到定义的函数,我需要要这样做:

Now, I have seen a code used to find the defined functions in a module, and I need to do something like this:

    for myitem in myItems:
        myDict[myitem] = ??? #to dynamically find the corresponding function

所以我的问题是,我如何列出所有的 Exec 函数,然后使用字典将它们分配给所需的项目?所以最后我会有 myDict [P1]()#this将调用ExecP1()

So my question is, How do I make a list of all the Exec functions and then assign them to the desired item using the a dictionary? so at the end I will have myDict["P1"]() #this will call ExecP1()

我真正的问题是我有这么多的项目,我做一个图书馆将处理他们,所以最终用户只需要调用 myMain(P1)

My real problem is that I have tons of those items and I making a library that will handle them so the final user only needs to call myMain("P1")

我认为使用检查模块,但我不太确定如何做。

I think using the inspect module, but I am not so sure how to do it.

我的原因是避免:

def ExecPn():
    pass
myDict["Pn"]=ExecPn

是我必须保护代码,因为我正在使用它来在我的应用程序中提供脚本功能。

is that I have to protect code as I am using it to provide a scripting feature within my application.

推荐答案

不为此感到自豪,但是:

Not proud of it, but:

def myMain(key):
    def ExecP1():
        pass
    def ExecP2():
        pass
    def ExecP3():
        pass
    def ExecPn():
        pass 
    locals()['Exec' + key]()

然而,我建议你把它们放在上面无论如何,这真的是可怕的。

I do however recommend that you put those in a module/class whatever, this is truly horrible.

这篇关于使用字典选择要执行的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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