找到指向某个对象的所有对象? (蟒蛇)

时间:2012-03-22 00:40:41

标签: python

如果我有某个对象的ID,例如,我怎样才能找到指向它的所有对象?

1 个答案:

答案 0 :(得分:1)

import gc

class Node(object):
    def __init__(self, data):
        self.data = data
        self.next = None

if __name__ == "__main__":
    a = Node(5)
    a.next = Node(4)
    a.next.next = Node(3)
    # returns a list of dictionary of the object(s) referring to a.next.next
    diction = gc.get_referrers(a.next.next)[0]
    diction['next'] = None
    print a.next.next

垃圾收集器有一些简洁的功能

get_referrers(...)
    get_referrers(*objs) -> list
    Return the list of objects that directly refer to any of objs.

get_referents(...)
    get_referents(*objs) -> list
    Return the list of objects that are directly referred to by objs.