Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:通过从字典中输入名称来创建函数_Python - Fatal编程技术网

Python:通过从字典中输入名称来创建函数

Python:通过从字典中输入名称来创建函数,python,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 c

我试图通过从给定字典中输入函数名来创建函数, 事实上,我不确定这是否可行,她就是我想做的:

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>
试试这个

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()
输出:

一些东西

一些东西

一些东西


在这种情况下,创建变量这样的函数从来都不是一个好主意,这表明您应该采取不同的方法来解决问题。对我来说,这似乎是一个错误。可能是重复的-但是,是的,这不太可能真的是正确的方式。看起来很像XY。你如何以动态的方式生成函数体?与代码总是相同的事实相比,为函数使用动态名称似乎是一个较小的问题。因此,这似乎毫无意义。对于那些能够跳出框框思考的人来说,这是一个非常好的主意。如果您知道答案,请添加它,如果您不知道,请不要哲学化地离开。@deceze用户希望从字典创建函数keys@deceze这不是你的工作