Python3技巧:动态变量名
- 2020 年 8 月 20 日
- 筆記
Firstly
各位应该做过服务器运维吧,像这样:
那么,在服务器运维的程序中,最好的访问服务器的方式是:运维库名.服务器名
由于服务器名是动态的,所以变量名也是动态的。今天我们就来讲讲Python3里面如何实现动态变量名。
globals函数
格式如下:
1 glabals()[字符串形式的变量名] = 值
这种方式只能设置全局变量。
例子:
import random x = random.randint(1,9) globals()['hel'+str(x)] = 9 print(globals())
输出:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'hel9': 9} >>> hel9 9
format函数+exec函数
格式:
#动态变量名 exec('''{0} = {1}'''.format(变量名,值)) #动态类名 exec('''class {0}: 代码'''.format(类名)) #动态函数名 exec('''def {0}: 代码'''.format(函数名))
这种方法可以定义动态变量名,动态类名、函数名。
例子:
exec('''b{0} = [1,2,3]'''.format(__import__('random').randint(1,9)))
print(globals())
输出:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>,'b4': [1, 2, 3]} >>> b4 [1,2,3]