函数转换为字符串不起作用。 如何在字符串中定义这个函数?
def func(x):
return x+1
def test(a,b):
loc = {'a':a,'b':b}
glb = {}
exec('c = [func(a+i)for i in range(b)]', glb,loc)
c = loc['c']
print(c)
print('out the function test()')
a= 1
b= 4
c = [func(a+i)for i in range(b)]
print(c)
'''结果:
out the function test()
[2, 3, 4, 5]
>>> test(1,4)
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
test(1,4)
File "C:\Users\Rosania\Documents\Edilon\Python examples\apagar.py", line 6, in test
exec('c = [func(a+i)for i in range(b)]', glb,loc)
File "<string>", line 1, in <module>
File "<string>", line 1, in <listcomp>
NameError: name 'func' is not defined
&#39;&#39;&#39;
答案 0 :(得分:2)
评估一个字符串是一种邪恶。
假设你知道自己在做什么......
Put&#34; func&#34;在当地人的dict也。您的eval环境必须知道您希望在eval&#d字符串中引用的所有内容。
loc = {'a':a, 'b':b, 'func':func}