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

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

问题描述

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

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 will call 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.

推荐答案

并不以此为傲,而是:

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.

如果你愿意为每个函数添加一个装饰器,你可以定义一个将每个函数添加到字典中的装饰器:

If you are willing to add a decorator for each function, you can define a decorator which adds each function to a dictionary:

def myMain(key):
    tasks = {}
    
    def task(task_fn):
        tasks[task_fn.__name__] = task_fn
    
    @task
    def ExecP1():
        print(1)
    @task
    def ExecP2():
        print(2)
    @task
    def ExecP3():
        print(3)
    @task
    def ExecPn():
        print(4)
    
    tasks['Exec' + key]()


另一种选择是将所有函数放在一个类(或不同的模块)下并使用getattr:

def myMain(key):
    class Tasks:
        def ExecP1():
            print(1)
        def ExecP2():
            print(2)
        def ExecP3():
            print(3)
        def ExecPn():
            print(4)
    
    task = getattr(Tasks, 'Exec' + key)
    task()

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

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