[英]How can we define a local variable just with its name(with a str)
I'm working on a pygame game, and I added a "console", and to be able to set a variable with my console.我正在开发一款 pygame 游戏,我添加了一个“控制台”,并且能够使用我的控制台设置一个变量。 So, when I type the command "set" it's going to take my 2 args: One is the variable name and the other is the value of my variable.
因此,当我键入命令“set”时,它将使用我的 2 个参数:一个是变量名,另一个是我的变量的值。 But the problem is, I can't find how to set the variable just the name.
但问题是,我找不到如何设置变量只是名称。
Here is an example:这是一个例子:
self.myVar = "ThisIsMyVar"
self.args = ['var', 'value']
# Here is where I check if the var exist in the code and if it is I want to add the value
#of self.args[1] to the self.myVar
Sorry if I explained it wrong but my English is not perfect, If you can help me I would be grateful !对不起,如果我解释错了,但我的英语不完美,如果你能帮助我,我将不胜感激!
Judging by self
, these are instance variables, not local variables.通过
self
判断,这些是实例变量,而不是局部变量。
In that case, you're in luck!在这种情况下,你很幸运!
setattr
will allow you to set an instance variable's value by name: setattr
将允许您按名称设置实例变量的值:
self.myVar = "ThisIsMyVar"
args = ['var', 'value']
setattr(self, args[0], args[1])
As people have mentioned in comments, a Python dictionary would be a good candidate here.正如人们在评论中提到的那样,Python 字典在这里将是一个不错的选择。
Python dictionaries are a bit like an indexed list, except that they can be indexed with a string too. Python 字典有点像索引列表,除了它们也可以用字符串索引。
console_variables = {} # empty dictionary to hold console "set" commands
So when the user enters the set
command in the console, eg: set colour red
:所以当用户在控制台输入
set
命令时,例如: set colour red
:
set_name, set_value = parseSetCommand( user_input ) # extract set command from input
console_variables[ set_name ] = set_value # save the setting
Later on, any string can be used to find items.稍后,任何字符串都可用于查找项目。 Say you also had a console command of
get
, such that they user could enter get colour
and expect it to output red
:假设您还有一个
get
控制台命令,这样他们的用户就可以输入get colour
并期望它为 output red
:
get_name = parseGetCommand( user_input ) # extract get command from input
if ( get_name in console_variables.keys() ): # does this set exist
consoleWrite( console_variables[ get_name ] ) # Yes: write it back
else:
consoleWrite( "[" + get_name + "] has not been set" ) # No: error
There's some simple dictionary examples here , if you want more examples.如果您想要更多示例,这里有一些简单的字典示例。 One thing to note is that dictionaries are case-sensitive, so in the above trying to find "Colour" in the dictionary would fail, because it's stored as "colour" (note the capital
C
).需要注意的一件事是字典区分大小写,因此在上面尝试在字典中查找“颜色”会失败,因为它存储为“颜色”(注意大写
C
)。 Your code could obviously handle this easily by storing and checking in the same capitalisation-case, maybe everything .lower()
.您的代码显然可以通过存储和检查相同的大写字母来轻松处理这个问题,也许一切都是
.lower()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.