2014-09-13 21 views
0

更多挖入蒔蘿。特別是給呼叫detect.at方法:dill.detect.at無法在'0x1023d2600'處引用對象

def _locate_object(address, module=None): 
    """get object located at the given memory address (inverse of id(obj))""" 
    special = [None, True, False] #XXX: more...? 
    for obj in special: 
     if address == id(obj): return obj 
    if module: 
     if PY3: 
      objects = iter(module.__dict__.values()) 
     else: 
      objects = module.__dict__.itervalues() 
    else: objects = iter(gc.get_objects()) 
    for obj in objects: 
     if address == id(obj): return obj 
    # all bad below... nothing found so throw ReferenceError or TypeError 
    from weakref import ReferenceError 
    try: address = hex(address) 
    except TypeError: 
     raise TypeError("'%s' is not a valid memory address" % str(address)) 
    raise ReferenceError("Cannot reference object at '%s'" % address) 

爲什麼我不能「搞定」這似乎是在地址字符串對象:4332529152

>>> class Parent(): 
...  name="Big Papa" 
...  def get_hitched(partner): 
...    return name + "+" + partner + "TLFE" 
... 
>>> johnny = Parent() 
    >>> johnny = Parent() 
>>> johnny.get_hitched("Mary") 
'Big Papa + Mary TLFE' 
>>> billy = johnny.get_hitched 
>>> billy("Junebug") 
'Big Papa + Junebug TLFE' 
>>> dill.detect.reference(billy) 
4299844816 
>>> dill.detect.reference(johnny.get_hitched) 
4299844816 
>>> dill.detect.reference(johnny) 
4299844816 
>>> dill.detect.reference(johnny.name) 
4332529152 
>>> dill.detect.reference(Parent) 
4332953328 
>>> dill.detect.at(4332529152) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/Users/mikekilmer/Envs/GLITCH/lib/python2.7/site-packages/dill/dill.py", line 738, in _locate_object 
    raise ReferenceError("Cannot reference object at '%s'" % address) 
ReferenceError: Cannot reference object at '0x1023d2600' 
>>> 0x1023d2600 
4332529152 
>>> id(johnny.name) 
4332529152 
>>> type(johnny.name) 
<type 'str'> 
+0

異常weakref.ReferenceError from weakref.ReferenceError:使用代理對象但收集基礎對象時引發的異常。這與標準ReferenceError異常相同。閱讀弱引用... – MikeiLL 2014-09-13 02:58:03

回答

1

Detect.at()獲取參考編號,如果它是由垃圾收集模塊處理的參考編號,則返回與其相關聯的對象。否則返回ReferenceError:和參考號的十六進制值。

例如,實例屬性不由GC管理,因爲它們在鏈接到的對象被銷燬時將被銷燬。

正如roippi說,在註釋:

所有他們在這裏做的是通過gc.get_objects搜索(),並通過ID比較對象 - 這是你究竟是如何應該使用的ID。無法解引用johnny.name的實際原因是,垃圾收集器不直接跟蹤類/實例屬性 - 不需要這樣做,因爲只要銷燬它們鏈接的對象就可以銷燬它們。

而十六進制數字只是在dill.detect.at()的參考號碼輸入上調用hex()方法的結果。

0

這裏的基本問題:對象的id()不是它的地址。它可能碰巧在CPython中,但它不是你可以使用的。我不知道應該使用什麼_locate_object,但看起來像基本上不好的代碼。你能解釋一下你真的想在這裏完成什麼嗎?

Python不適用於內存地址,它可以與對象引用一起使用。每個對象都有一個標識,它是一個整數。一些Pythons只需要在id()被請求時分配順序整數,僅此而已。您可以確定的是,同時存在的兩個不同對象具有相同的ID,並且對象的ID在其整個生命週期中都不會更改。

+0

1)代碼來自'dill',一個(流行的)第三方庫和2)該函數在'gc.get_objects()'中搜索值,該值是'id'返回相同的唯一標識符。 – roippi 2014-09-13 05:39:39

+0

其實我所要做的就是理解蒔蘿中的detect.at函數應該做什麼。它應該如何工作,以及什麼樣的體例用例。 – MikeiLL 2014-09-13 13:10:40

+1

我無法幫到那裏。我只能說,id()沒有返回一個地址,所以根本無法取消它。你所能做的就是嘗試找到一個匹配的對象。如果你保留了一個對象的id而沒有保留對它的引用,你就會冒這個對象不再存在,而另一個對象獲得相同的id,因爲id可以被重用。 – rosuav 2014-09-13 13:15:00