python中globals()的用法
1. 获取所有的全局变量, 获取到的内容如下:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7efc4bd1d960>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home//WorkSpace/tmp/try_globals.py', '__cached__': None, 'a': 10, 'f': <function f at 0x7efc4d0abd90>}
相应有`locals()`变量可以用来获取局部变量.
2. 用于概据变量名的内容来生成新的变量.
比如, 用字符串a的内容, 来生成一个新变量并赋值. 算是比较tick的用法, 感觉上比用eval生成变量名安全一点???
a = 'apple' b = 'banana' c = 'orange' globals()[a]=1 globals()[b]=2 globals()[c]=3 print(globals()) 输出内空: {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f8dcf121960>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/ckboss/WorkSpace/tmp/try_globals.py', '__cached__': None, 'a': 'apple', 'b': 'banana', 'c': 'orange', 'apple': 1, 'banana': 2, 'orange': 3} 没有显示定义, 但下面三个变量已经生成好了. print(apple) print(banana) print(orange)
标签:__,None,python,用法,orange,globals,print,banana From: https://www.cnblogs.com/JiangOil/p/17520829.html