代码之家  ›  专栏  ›  技术社区  ›  rxmnnxfpvg

Python定义动态函数

  •  13
  • rxmnnxfpvg  · 技术社区  · 14 年前

    我有这样的功能:

    def activate_field_1():
       print 1
    
    def activate_field_2():
       print 2
    
    def activate_field_3():
       print 3
    

    我该如何定义 activate_field_[x] x=1:10

    4 回复  |  直到 5 年前
        1
  •  20
  •   endolith    8 年前

    您想在源文件中静态地分别定义这些吗?那么最好的选择就是编写一个脚本来生成它们。

    另一方面,如果在运行时需要这些函数,可以使用高阶函数。例如。

    >>> def make_func(value_to_print):
    ...     def _function():
    ...         print value_to_print
    ...     return _function
    ...
    >>> f1 = make_func(1)
    >>> f1()
    1
    >>> f2 = make_func(2)
    >>> f2()
    2
    

    >>> my_functions = [make_func(i) for i in range(1, 11)]
    >>> for each in my_functions:
    ...     each()
    ...
    1
    2
    3
    ...
    
        2
  •  11
  •   martineau    5 年前

    确切地 Dynamic/runtime method creation accepted answer 在@Goutham现在删除的答案中提到):

    FUNC_TEMPLATE = """def activate_field_{0}(): print({0})"""
    for x in range(1, 11): exec(FUNC_TEMPLATE.format(x))
    
    >>> activate_field_1()
    1
    >>> activate_field_7()
    7
    

    f-string 文字:

    for x in range(1, 11): exec(f"""def activate_field_{x}(): print({x})""")
    
        3
  •  5
  •   Andrey Vlasovskikh    14 年前

    vars() :

    for i in range(1, 11):
        def f(x):
            def g():
                print x
            return g
        vars()['activate_field_%d' % i] = f(i)
    
    >>> activate_field_3()
    3
    

    但是这个技巧通常不会被推荐,除非你确定你需要它。

        4
  •  3
  •   Odomontois    14 年前

    from functools import partial
    class FunctionPool:
        def __init__(self,function):
            self.function = function
        def __getitem__(self,item):
            return partial(self.function,item)
    
    >>> @FunctionPool
    def func(item,param):
        print "function#{item} called with {param}".format(
            item = item,
            param = param )
    >>> f = func[2]
    >>> f(3)
    function#2 called with 3