Python:通过从字典中提供名称来创建函数

时间:2018-03-05 08:35:58

标签: python

我尝试通过给出字典中的函数名来创建函数, 实际上,我不确定这是否可行,她正是我想要做的事情:

def functions_factory(my_dict):
        for the name in my_dict:
            create_function(name)

def   create_function(function_name):
        x=0
        # **code implentation:** here should write a code that can create function with name = <function_name>

1 个答案:

答案 0 :(得分:0)

试试这个

one = 'one'
two = 'two'
three = 'three'
l = {one:1, two:2, three:3}
def some_stuff():
    print("some stuff")
for keys,item in l.items():
    def _f():
        some_stuff()
    globals()[keys] = _f
    del _f

one()
two()
three()

输出:

  

一些东西

     

一些东西

     

一些东西