Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/logging/2.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,我读过几篇关于闭包之类的文章,但我正在尝试创建一个特定的命名函数 from app.conf import html_helpers # html_helpers = ['img','js','meta'] def _makefunc(val): def result(): # Make this name of function? return val() return result def _load_func_from_module(module_li

我读过几篇关于闭包之类的文章,但我正在尝试创建一个特定的命名函数

from app.conf import html_helpers

# html_helpers = ['img','js','meta']

def _makefunc(val):
    def result(): # Make this name of function?
        return val()
    return result

def _load_func_from_module(module_list):
    for module in module_list:
        m = __import__("app.system.contrib.html.%s" % (module,), fromlist="*")
        for attr in [a for a in dir(m) if '_' not in a]:
            if attr in html_helpers and hasattr(m, attr):
                idx = html_helpers.index(attr)
                html_helpers[idx] = _makefunc(getattr(m,attr))

def _load_helpers():
    """ defines what helper methods to expose to all templates """
    m = __import__("app.system.contrib.html", fromlist=['elements','textfilter'])
    modules = list()
    for attr in [a for a in dir(m) if '_' not in a]:
        print attr
        modules.append(attr)
    return _load_func_from_module(modules)
当我调用_load_helpers时,img会像这样返回一个修改过的字符串。我想将现有字符串列表修改为我调用的那些函数

这是可能的吗?因为我感到困惑,我说得有道理吗:(

我想我应该做你想做的事:

from functools import wraps

def _makefunc(val):
    @wraps(val)
    def result():
        return val()
    return result

>>> somefunc = _makefunc(list)
>>> somefunc()
[]
>>> somefunc.__name__
'list'