简体   繁体   English

我们如何只用它的名字定义一个局部变量(用一个str)

[英]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.

相关问题 为什么我们必须定义变量 dp = [0] * (n+1) 只是为了将其变量设置为等于 0(在动态规划中) - Why we have to define variable dp = [0] * (n+1) just to set its variable equal to 0( In Dynamic Programming) 我们如何在python中打印变量名及其值,这在调试期间是否有用? - How can we print the variable name along with its value in python, which will be useful during debugging? 如何将`str`中的变量名和值添加到类中? - How can I add variable name and value from `str` to a class? 我们可以在python中定义具有多个索引的变量吗? - can we define a variable with multi indices in python? 我可以定义如何处理访问 python object(而不仅仅是它的属性)吗? - Can I define how accessing python object (and not just its attributes) is handled? 如何在变量名称的第二个字符旁调用变量? - How can I call for a variable by the second character on its name? 我们如何“手动” /明确定义一个类? - How can we “manually”/explicity define a class? 为什么我们不能将方法或类名定义为字符串? - Why we can not define method or class name as a string? 如何定义 function 以基于另一个变量创建具有特定名称的变量? (Python 3) - How can I define a function to create a variable with an especific name based on another variable? (Python 3) 如何使用str动态指向一个变量来更新它的值 - How to point to a variable dynamically using str to update its value
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM