Python:通过gitting字典中的名称来创建函数

2024-04-25 23:41:39 发布

您现在位置: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>

Tags: the函数nameinfor字典myfactory
1条回答
网友
1楼 · 发布于 2024-04-25 23:41:39

试试这个

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()

输出:

some stuff

some stuff

some stuff

相关问题 更多 >