vars() 函数

vars()函数属于Python标准库提供的内置函数,返回关联对象的__dic__属性
vars()函数仅接受一个参数,以具有__dict__属性的对象作为参数,

>>> a = 5
>>> astr = 'hello'
>>> vars()['a']
5
>>> vars()['astr']
'hello'
>>> scope = vars()
>>> scope["astr"]
'hello'

  

如果不带参数使用 vars() ,则会显示包含本地符号表的字典

>>> vars()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'a': 5, 'astr': 'hello'}

>>> locals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'a': 5, 'astr': 'hello'}

  

不带参数时,vars() 的行为类似locals()

 

globals()始终返回模块名称空间的字典
locals()始终返回当前名称空间的字典
vars()返回当前名称空间的字典(如果不带参数调用)或参数的字典。

 

posted @ 2023-05-30 14:53  sangern  阅读(89)  评论(0)    收藏  举报