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]