首页 > 解决方案 > 如何使用已编译的 Code 对象创建 Function 对象?

问题描述

所以我有以下代码。

code_string = """def f1(p1, p2, p3):
    print("a{}, b{}, c{}".format(p1, p2, p3))
def f2():
    print("text")
"""

code = compile(code_string, '<string>', 'exec')

f1 = code.co_consts[0]
f2 = code.co_consts[2]  # code.co_consts is the name of the prior function ("f1")

它将带有一些函数的字符串编译成代码对象,然后将函数的代码对象存储到单独的变量中。

我想知道的是如何使用上面的代码对象创建函数对象,以便我可以调用它们。

所以说ff1 = new_function(f1)在哪里,我isinstance(ff1, types.FunctionType)可以Trueff1('a', 'b', 'c')print "aa, bb, cc"

f1中的代码对象f2可以使用 exec 来执行。(虽然我不知道如何以f1这种方式将参数传递给它们或用它们制作绑定方法)

标签: pythonfunction

解决方案


您可以使用exec(code)and执行代码,f1之后f2您可以使用。

code_string = """def f1(p1, p2, p3):
    print("a{}, b{}, c{}".format(p1, p2, p3))
def f2():
    print("text")
"""

code = compile(code_string, '<string>', 'exec')
exec(code)

f1(1, 2, 3)
# a1, b2, c3
f2()
# text

请理解,将任意代码传递给exec()(或evil eval())会带来严重的安全风险。


推荐阅读