我一直認爲在Python解釋器值x.__class__
和type(x)
是等效的。但是,如果我們做到以下幾點(在Python 2.7,3.3和也PyPy 2.0b1):類型的行爲與weakref - 不明白
>>> import weakref
>>> x = set()
>>> y = weakref.proxy(x)
>>> x.__class__, isinstance(x, set), type(x)
(<type 'set'>, True, <type 'set'>)
>>> y.__class__, isinstance(y, set), type(y)
(<type 'set'>, True, <type 'weakproxy'>)
我們將看到y.__class__
對應於包裹類型weakref.proxy
(我想,weakref.proxy
只是取代了僞裝的屬性)。即使isinstance
將y
標識爲set
。
但是type
顯示「真」類型 - weakproxy
。因此,type
不使用__class__
屬性來標識參數的類型,是嗎?它是否爲此目的使用了一些「更可靠」的來源?如果是這樣,我們可以直接訪問它嗎?
謝謝你的回答。 關於'isinstance'。它是否首先檢查'ob_type',然後如果它不等於'__class__'? – 2013-03-26 09:06:49
@IvanYurchenko,粗略地說,是的,先是'ob_type',然後是'__class__'。實際上,它們之間有一個特殊的鉤子['__instancecheck__'](http://docs.python.org/2/reference/datamodel.html?highlight=__instancecheck__#class.__instancecheck__)。 – nymk 2013-03-26 09:43:41
謝謝@nymk。 – 2013-03-26 10:55:57