問題描述
誰能用足夠的例子向我解釋一下b/w有什么區(qū)別
Can anybody explain to me with adequate examples whats the difference b/w
>>> import inspect
>>> inspect.getmembers(1)
和
>>> type(1).__dict__.items()
和
>>> dir(1)
除了它們顯示出減少的屬性數(shù)量和按順序排列的方法.1 是整數(shù)(但它可以是任何類型.)
except that they show an decreasing no.s of attributes & methods in that order. 1 is integer (but it can be of any type.)
編輯
>>>obj.__class__.__name__ #gives the class name of object
>>>dir(obj) #gives attributes & methods
>>>dir() #gives current scope/namespace
>>>obj.__dict__ #gives attributes
推薦答案
dir()
允許您通過定義 __dir__()
自定義對(duì)象報(bào)告的屬性.
dir()
allows you to customize what attributes your object reports, by defining __dir__()
.
從手冊(cè)中,如果 __dir__()
沒有定義:
From the manual, if __dir__()
is not defined:
如果對(duì)象是模塊對(duì)象,則列表包含模塊屬性的名稱.
If the object is a module object, the list contains the names of the module’s attributes.
如果對(duì)象是類型或類對(duì)象,則列表包含其屬性的名稱,并遞歸地包含其基類的屬性.
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.
否則,列表包含對(duì)象的屬性名稱、其類屬性的名稱,以及其類的基類屬性的遞歸名稱.
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.
這也是 inspect.getmembers()
返回的內(nèi)容,只不過它返回的是 (name, attribute)
的元組,而不僅僅是名稱.
This is also what inspect.getmembers()
returns, except it returns tuples of (name, attribute)
instead of just the names.
object.__dict__
是 {key: attribute, key2: atrribute2}
等形式的字典.
object.__dict__
is a dictionary of the form {key: attribute, key2: atrribute2}
etc.
object.__dict__.keys()
有其他兩個(gè)所缺少的.
object.__dict__.keys()
has what the other two are lacking.
來自 inspect.getmembers()
上的文檔:
當(dāng)參數(shù)是一個(gè)類時(shí),getmembers() 不返回元類屬性(此行為繼承自 dir() 函數(shù)).
getmembers() does not return metaclass attributes when the argument is a class (this behavior is inherited from the dir() function).
對(duì)于 int.__dict__.keys()
,這是
['__setattr__', '__reduce_ex__', '__reduce__', '__class__', '__delattr__', '__subclasshook__', '__sizeof__', '__init__']
總結(jié)一下,dir()
和inspect.getmembers()
基本相同,而__dict__
是包含元類屬性的完整命名空間.
To summarize, dir()
and inspect.getmembers()
are basically the same, while __dict__
is the complete namespace including metaclass attributes.
這篇關(guān)于inspect.getmembers() vs __dict__.items() vs dir()的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!