python中__dict__与dir()的区别

  在python中__dict__与dir()都可以返回一个对象的属性,区别在于:

  • __dict__是对象的一个属性,而dir()是一个built-in的方法;
  • __dict__返回一个对象的属性名和值,即dict类型,而dir()返回一个属性名的list
  • __dict__不是每一个对象都有,而dir()对各种类型对象都起作用,如module, type, class, object;
  • _dict__只返回对象的可写属性(writable attributes),而dir()返回各种相关(relavent)属性,且对于不同类型对象,作用不同

 

2.7版官方文档描述如下:

__dict__

object.__dict__
A dictionary or other mapping object used to store an object’s (writable) attributes.

dir()

The default dir() mechanism behaves differently with different types of objects, as it attempts to produce the most relevant, rather than complete, information:

  • If the object is a module object, the list contains the names of the module’s attributes.
  • If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases.
  • Otherwise, the list contains the object’s attributes’ names, the names of its class’s attributes, and recursively of the attributes of its class’s base classes.
posted @ 2018-12-25 16:55  tlz888  阅读(984)  评论(0编辑  收藏  举报