2011-03-21 34 views
9
>>> class foo(object): 
...  def test(s): 
...   pass 
... 
>>> a=foo() 
>>> a.test is a.test 
False 
>>> print a.test 
<bound method foo.test of <__main__.foo object at 0x1962b90>> 
>>> print a.test 
<bound method foo.test of <__main__.foo object at 0x1962b90>> 
>>> hash(a.test) 
28808 
>>> hash(a.test) 
28808 
>>> id(a.test) 
27940656 
>>> id(a.test) 
27940656 
>>> b = a.test 
>>> b is b 
True 
+0

對不起,什麼? – Mat 2011-03-21 22:45:39

回答

7

它們在運行時綁定;每次訪問對象上的屬性都會重新引用該方法。當你將兩者都放在同一行時,他們不同的原因是第一個方法在第二個方法被綁定時沒有被釋放。

+8

換句話說,'id'每次看起來都是一樣的,因爲之前的實例在打印結果後立即被gc'd處理過,並且該特定版本的CPython中的內存管理恰好足夠可預測,以使下一個對象處於相同的狀態地點。 – delnan 2011-03-21 23:02:45

+0

哈哈它從來沒有想過我GC將重新定位在同一地址。謝謝這一切都是有道理的。 – 2011-03-23 03:45:03

相關問題