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.


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM