What would you do if you were to write a program that had X1 for 1,X2 2 and then until X100 was 100?
In a static language like C, the variable name is actually translated directly into the memory address by the compiler, so there is no way to do this except manually setting the value of each variable. And Python is a dynamic language that can do that.
The easiest thing to think of is the eval, but in fact there is no need for such dangerous things, because Python's variable name is a dictionary key. To get the dictionary, just use the locals and Globals functions.
So this program can be implemented like this:
The code is as follows:
>>> names = locals ()
>>> for I in xrange (1, 101):
... names[' x%s '% i] = i
...
>>> x1
1
>>> x2
2
>>> x100
100
But you may say that this example is useless, after all, it is more practical to use arrays.
So consider one more example: The server uses an object database that can be stored directly in the database. The server lists all the classes that are currently supported, and the user wants to add a class that does not exist in the list, and then sends a JSON or XML text to the server. The server parses the text, converts it to a class object, and sets the class name. The user is then free to generate objects of this class.
The key is that the database is related to the class name, you can't use a generic object class to hold all the objects, otherwise the query will be messed up.
And coincidentally, there are people in the Gae forum to put forward this demand, and only Java he finally can only give up.
Of course, if you want to use a spoof, you can:
The code is as follows:
>>> locals () [' True '] = False
>>> True
False
Another use is to test whether a variable name already exists. The standard practice is to try...except a Nameerror exception, which can be judged directly in locals () or in Globals ().
By the way, another strange way, do not know that someone has written:
The code is as follows:
>>> Import __main__
>>> hasattr (__main__, ' x ')
False
>>> setattr (__main__, ' X ', 1)
>>> x
1
>>> hasattr (__main__, ' x ')
True
Of course, no one is recommending you to write like this, nor will I.
Finally, in addition to dynamically setting variable names, dynamic deletion is also possible, for example del locals () [' X1 ']. Similarly, delattr is also available.