Home > Article > Backend Development > Python implements variable variable names
This article mainly introduces the method of using dynamic variable names in Python. Friends who need it can refer to it
If you want to write a program , let x1 be 1, x2 be 2, and then until x100 is 100, what would you do?
In a static language like C, the identifier of the variable name will actually be directly translated into a memory address by the compiler, so there is no way to do this except manually setting the value of each variable. And dynamic languages like Python can do it.
The easiest thing to think of is naturally eval, but in fact there is no need for such a dangerous thing, because Python's variable name is just a dictionary key. To obtain this dictionary, just use the locals and globals functions directly.
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 an array to implement it.
Then consider another example: the server uses an object database and can directly save objects into the database. The server lists all currently supported classes, and the user wants to add a class that does not exist in the list, so a JSON or XML text is sent to the server. The server parses this text, converts it into a class object, and sets the class name. The user can then generate objects of this class at will.
The key is that this database is related to the class name. You cannot use a general Object class to save all objects, otherwise the query will be messed up.
Coincidentally, someone also raised this requirement on the GAE forum, but he, who only knew Java, had to give up in the end.
Of course, you can use it as a prank:
The code is as follows:
>>> locals()['True'] = False >>> True False
Another use is to test whether a variable name already exists. The standard approach is to try...except a NameError exception. In fact, you can directly use in locals() or in globals() to judge.
By the way, let me introduce another strange method. I don’t know if anyone has written it like this:
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 recommends you to write like this, and neither do I. meeting.
Finally, in addition to dynamically setting variable names, dynamic deletion is also possible, such as del locals()['x1']. Likewise, delattr is available.
Related tutorial recommendations: Python video tutorial
The above is the detailed content of Python implements variable variable names. For more information, please follow other related articles on the PHP Chinese website!