我可以使用'function'类创建函数吗?

时间:2013-01-31 16:26:16

标签: python python-3.x

我想知道,只是为了好玩,如果我可以使用 function 类构造函数创建函数,即没有语言构造 def ,就像通过实例化类型创建类一样宾语。我知道,函数构造函数需要2个参数 - 代码对象和全局变量。但我不知道如何正确地编译源。

>>> def f(): 
...     pass

>>> Function = type(f) 
>>> Function
<class 'function'>
>>> code = compile("x + 10", "<string>", "exec")
>>> f = Function(code, globals())
>>> f()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'x' is not defined
>>> f(20)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: <module>() takes 0 positional arguments but 1 was given

2 个答案:

答案 0 :(得分:4)

您需要在代码对象上设置许多属性,例如co_varnames,co_nlocals等。 显而易见的是

code = compile("def foo(n):return n+10", "<string>", "exec").co_consts[0]
func = Function(code, globals())

但我想这会被视为作弊。要从头开始真正定义代码对象,请执行(对于3.3)

code = types.CodeType(1, 0, 1, 2, 67, b'|\x00\x00d\x01\x00\x17S', (None, 10), 
                      (), ('x',), '<string>', 'f', 1, b'\x00\x01')
func = Function(code, globals())
print(func(10))

当然,这需要你自己完成整个编译()。

答案 1 :(得分:0)

嗯,这很有效:

>>> x = 0
>>> def f(): pass
... 
>>> func = type(f)
>>> code = compile("global x\nx += 10","<string>","exec")
>>> nf = func(code,globals())
>>> nf()
>>> x
10

不知道如何将参数传递给函数。