简体   繁体   English

如何使用“exec”按名称选择变量

[英]How do I select a variable by its name using 'exec'

I have an issue I am struggling to fix.我有一个我正在努力解决的问题。 I need to make an input that will allow the user to name a variable, but how would I then use this variable?我需要做一个允许用户命名变量的输入,但是我将如何使用这个变量?

To make it I just have to do:要做到这一点,我只需要做:

a = input('var name?')
exec(a) 

So if the user enters 'dog' that will be a variable called dog , but how do I then use this variable?因此,如果用户输入 'dog' 这将是一个名为dog的变量,但是我该如何使用这个变量呢? I don't have its name so is it even possible?我没有它的名字所以它甚至可能吗?

Additionally, how do I make it a global variable if it's in a function?另外,如果它在一个函数中,我如何使它成为一个全局变量? Sorry about my bad grammar and English.抱歉我的语法和英语不好。 I am not really sure what to try.我不确定要尝试什么。

So, you can do this, but I'm not sure why you would.所以,你可以这样做,但我不确定你为什么会这样做。 Whatever you do, don't use exec for the reasons brought up by Tagc in the comments.无论你做什么,都不要因为 Tagc 在评论中提出的原因而使用exec

>>> a = input('var name? ')
var name? dog
>>> globals()[a] = 'hi everyone'
>>> dog
'hi everyone'

And you do have the name, it's in a , and you can access it in globals() :而且有名字,它是在a ,你可以访问它globals()

>>> globals()[a]
'hi everyone'
>>>

But this just brings the point home: why not just use a dict instead of the globals() dict ?但这只是把重点带回家:为什么不使用dict而不是globals() dict

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM