小编vas*_*aur的帖子

如何从字符串中获取python函数对象

我有字符串格式的 python 函数,我想在程序范围内获取这些函数的 python 对象。我已经尝试过exec()eval()ast.literal_eval()这些都没有返回函数对象。

例如:

s = "def add(args):\n    try:\n        return sum([int(x) for x in args])\n    except Exception as e:\n        return 'error'\n
Run Code Online (Sandbox Code Playgroud)

这是字符串中的一个简单函数,用于添加列表元素。我正在寻找一个可以返回函数对象的实用模块add

function_obj = some_function(s)
print 'type:', type(function_obj)
type: <type 'function'>
Run Code Online (Sandbox Code Playgroud)

python python-2.7

4
推荐指数
1
解决办法
2142
查看次数

标签 统计

python ×1

python-2.7 ×1