Python: 在运行时动态创建函数

如何在 Python 中动态创建函数?

我在这里看到了一些答案,但是我找不到一个能够描述最一般情况的答案。

考虑一下:

def a(x):
return x + 1

如何在运行中创建这样的函数?我一定要 compile('...', 'name', 'exec')吗?然后呢?创建一个虚拟函数并替换其代码对象,然后从编译步骤之一?

或者我应该使用 types.FunctionType? 如何?

我想自定义一切: 参数的数量,它们的内容,代码在函数体,结果,..。

82748 次浏览

使用 exec:

>>> exec("""def a(x):
...   return x+1""")
>>> a(2)
3

你看到 这个了吗,这个例子告诉你如何使用 types.FunctionType

例如:

import types


def create_function(name, args):
def y(): pass


y_code = types.CodeType(args,
y.func_code.co_nlocals,
y.func_code.co_stacksize,
y.func_code.co_flags,
y.func_code.co_code,
y.func_code.co_consts,
y.func_code.co_names,
y.func_code.co_varnames,
y.func_code.co_filename,
name,
y.func_code.co_firstlineno,
y.func_code.co_lnotab)


return types.FunctionType(y_code, y.func_globals, name)


myfunc = create_function('myfunc', 3)


print repr(myfunc)
print myfunc.func_name
print myfunc.func_code.co_argcount


myfunc(1,2,3,4)
# TypeError: myfunc() takes exactly 3 arguments (4 given)

这个方法怎么样?

在这个例子中,我是一个类中一个变量(x-> ax + b)上的 参数化一阶函数:

class Fun:
def __init__(self, a,b):
self.a, self.b = a,b


def f(self, x):
return (x*self.a + self.b)


u = Fun(2,3).f

这里 u是函数 x-> 2x + 3。

如果你需要从一个特定的模板动态创建一个函数,可以试试这个:

def create_a_function(*args, **kwargs):


def function_template(*args, **kwargs):
pass


return function_template


my_new_function = create_a_function()

在函数 Create _ a _ function ()中,您可以控制要选择的模板。内部函数 Function _ template 函数 _ 模板充当模板。创建函数的返回值是一个函数。赋值后使用 我的新功能作为常规函数。

通常,此模式用于函数修饰符,但在这里也可能很方便。

你可以用 lambda。

a = lambda x: x + 1
>>> a(2)
3

你可以这样做:

new_func='def next_element(x):\n  return x+1'
the_code=compile(new_func,'test','exec')
exec(the_code)
next_element(1)

它类似于以前的执行解决方案。

比贝尔西的回答更简单

def get_fn(a, b): # factory function
def fn(): # result function
print(a, b)
return fn


fn = get_fn(1, 2)


fn()

这对于将变量转换为常量(“动态函数的模板变量”)很有用