Python:在运行时动态创建函数 [英] Python: dynamically create function at runtime

查看:660
本文介绍了Python:在运行时动态创建函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我在这里看到了一些答案,但是我找不到一个可以描述最常见情况的答案。 p>

考虑:

  def a(x):
return x + 1

如何快速创建这样的功能?我需要编译('...','name','exec')它吗?但是呢?创建一个虚拟函数,并从编译步骤替换它的代码对象?



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



我想定制一切:参数的数量,它们的内容,函数体中的代码,结果,...
exec

 

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


How to dynamically create a function in Python?

I saw a few answers here but I couldn't find one which would describe the most general case.

Consider:

def a(x):
    return x + 1

How to create such function on-the-fly? Do I have to compile('...', 'name', 'exec') it? But what then? Creating a dummy function and replacing its code object for then one from the compile step?

Or should I use types.FunctionType? How?

I would like to customize everything: number of argument, their content, code in function body, the result, ...

解决方案

Use exec:

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

这篇关于Python:在运行时动态创建函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆