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