实现效果:执行字符串形式的函数
代码如下
1 # name = 'aaa' 2 # data = [18,32,33] 3 # def hellocute(): 4 # return "name %s ,age %d" %(name,data[0]) 5 # a = hellocute() 6 # print(a) 7 namespace = { 'name':'aaa','data':[18,32,33]} 8 code = """def hellocute():return "name %s ,age %d" %(name,data[0])""" 9 fun = compile(code,'','exec')10 exec(fun,namespace)11 print(namespace)12 ret = namespace['hellocute']()13 print(ret)