博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

python内置函数之vars()

Posted on 2017-10-17 16:34  开飞机的贝塔  阅读(1858)  评论(0编辑  收藏  举报
vars([object])

返回__dict__属性的值。
当不传入参数时,和locals()等效。
当函数接收一个参数时,参数可以是模块、类、类实例,或者定义了__dict__属性的对象。

>>> vars(A)
mappingproxy({'__module__': '__main__', 'infoA': 'A', '__dict__': <attribute '__dict__' of 'A' objects>,
 '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None})
>>> class B:
...   __dict__ = 'tom'
...
>>> b = B()
>>> b.__dict__
'tom'
>>> vars(b)
'tom'

 

拓展

模块都有__dict__属性。

这是包含模块符号表的字典。

修改这个字典实际上会改变模块的符号表,但直接赋值给__dict__属性是不可能的(你可以写m .__ dict __ ['a'] = 1,将ma定义为1,但是你不能写m .__ dict__ = {})。

不建议直接修改__dict__

模块表示方法

#内置模块
>>> json
<module 'json' from 'D:\\python\\python3.6\\lib\\json\\__init__.py'>
#非内置模块
>>> sys
<module 'sys' (built-in)>