python - python从字符串中获取函数

标签 python

是否可以定义一个函数来表现如下?

text = "def x(a):\treturn a+1"
f = ??(text)
f(1)
>> 2

最佳答案

你可以使用exec()

text = "def x(a):\treturn a+1"
exec(text)
print x(5) # gives 6

关于python - python从字符串中获取函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28720236/

相关文章:

python - 当 EB 环境为 python 3.6 时,使用 python 2.7 安装要求时出现 AWS 错误

python - 属性错误 : module 'tensorflow' has no attribute 'GraphDef'

python - 仅对列表中包含的数字求和

python - 使用列表理解对数据帧的子集进行切片

python - 是否有一个 Python 库可以简化 CLI 实用程序(如 Django 管理命令)的创建?

python - 如何在Python中正确处理记录器文件大小?

generator - 这是素数生成器 pythonic

python - Emacs python 自动补全

python - 如何删除包含零的 numpy 数组中的一行?

python - 来自 Get Name into a List 的 Tkinter 信息