开发者

python string to code for function arg?

I have a function names "myfunction". I have a string "a", I need to pass it to "myfunction" so it will give the same result as if my string was a python object name, myfunction(a) So I 开发者_C百科have

def myfunction(var):
    print var
a = 1
mystring = "a"

I need to pass "mystring" to "myfuntion" so it will behave as variable "a" was passed to it. I thought of something like this, but it won't work:

myfunction(exec(mystring))

PS. Yes, I know of the consequences of exec(), please there is no need to explain that.


It would be eval(), not exec:

myfunction(eval(mystring))

Alternatively:

myfunction(locals()[mystring])

Most probably you have a fundamental design problem if you think you need something like this.


No needs in exec or eval:

>>> def myfunc(var):
...     print globals()[var] * 2
...
>>> a = 12
>>> myfunc('a')
24
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜