如何从函数中的exec返回值? [英] How to return value from exec in function?
本文介绍了如何从函数中的exec返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试:
def test(w,sli):
s = "'{0}'{1}".format(w,sli)
exec(s)
return s
print test("TEST12344","[:2]")
其返回"TEST12344" [:2]
its return 'TEST12344'[:2]
如何从函数中的exec返回值
How to return value from exec in function
推荐答案
exec()
不仅评估表达式,还执行代码.您必须在exec()
调用中保存参考.
exec()
doesn't just evaluate expressions, it executes code. You would have to save a reference within the exec()
call.
def test(w, sli):
exec('s = "{}"{}'.format(w, sli))
return s
如果只想计算一个表达式,请使用eval()
,并保存对返回值的引用:
If you just want to evaluate an expression, use eval()
, and save a reference to the returned value:
def test(w,sli):
s = "'{0}'{1}".format(w,sli)
s = eval(s)
return s
但是,我建议尽可能避免在任何实际代码中使用exec()
和eval()
.如果使用它,请确保有充分的理由这样做.
However, I would recommend avoiding exec()
and eval()
in any real code whenever possible. If you use it, make sure you have a very good reason to do so.
这篇关于如何从函数中的exec返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文