Python中使用动态变量名的方法
如果要写一个程序,让x1为1,x2为2,然后直到x100为100,你会怎么做?
在C这种静态语言里,变量名这个标识符实际上会被编译器直接翻译成内存地址,所以除了手动设置每个变量的值以外,没办法做到这点。而Python这种动态语言则是可以做到的。
最容易想到的自然是eval,但是实际上根本不需要这种危险的东西,因为Python的变量名就是一个字典的key而已。要获取这个字典,直接用locals和globals函数即可。
因此这个程序可以这样实现:
代码如下:
>>> names = locals()
>>> for i in xrange(1, 101):
... names['x%s' % i] = i
...
>>> x1
1
>>> x2
2
>>> x100
100
不过你也许会说这个例子没什么用,毕竟用数组来实现更为实用。
那么再考虑一个例子:服务器使用一种对象数据库,可以直接保存对象到数据库中。服务器列出目前支持的所有类,而用户想添加一个不存在于列表中的类,于是向服务器发送一段JSON或XML文本。服务器解析这段文本,将它转换成一个class对象,并且设置类名。之后用户就可以随意生成这个类的对象。
关键是这个数据库和类名相关,你不能用一个通用的Object类来保存所有的对象,否则查询时就乱套了。
而恰巧的是,还就有人在GAE论坛上提出了这个需求,而只会Java的他最终只能放弃。
当然,你想用来恶搞也行:
代码如下:
>>> locals()['True'] = False
>>> True
False
另一个用处就是测试一个变量名是否已经存在。标准的做法是try...except一个NameError异常,实际上直接用in locals()或in globals()就能判断了。
顺便再介绍另一种奇怪的方法,不知道有人这样写过没:
代码如下:
>>> import __main__
>>> hasattr(__main__, 'x')
False
>>> setattr(__main__, 'x', 1)
>>> x
1
>>> hasattr(__main__, 'x')
True
当然,没有任何人推荐你这样写,我也不会。
最后,除了动态设置变量名,动态删除也是可以的,例如del locals()['x1']。同样,delattr也是可用的。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".
