简体   繁体   中英

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. 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. 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.

In that case, you're in luck! setattr will allow you to set an instance variable's value by name:

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 dictionaries are a bit like an indexed list, except that they can be indexed with a string too.

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_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_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 ). Your code could obviously handle this easily by storing and checking in the same capitalisation-case, maybe everything .lower() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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