Weak References in python

后端 未结 4 2204
醉梦人生
醉梦人生 2021-01-30 10:37

I have been trying to understand how python weak reference lists/dictionaries work. I\'ve read the documentation for it, however I cannot figure out how they work, and what the

4条回答
  •  感动是毒
    2021-01-30 10:53

    Theory

    The reference count usually works as such: each time you create a reference to an object, it is increased by one, and whenever you delete a reference, it is decreased by one.

    Weak references allow you to create references to an object that will not increase the reference count.

    The reference count is used by python's Garbage Collector when it runs: any object whose reference count is 0 will be garbage collected.

    You would use weak references for expensive objects, or to avoid circle references (although the garbage collector usually does it on its own).

    Usage

    Here's a working example demonstrating their usage:

    import weakref
    import gc
    
    class MyObject(object):
        def my_method(self):
            print 'my_method was called!'
    
    obj = MyObject()
    r = weakref.ref(obj)
    
    gc.collect()
    assert r() is obj #r() allows you to access the object referenced: it's there.
    
    obj = 1 #Let's change what obj references to
    gc.collect()
    assert r() is None #There is no object left: it was gc'ed.
    

提交回复
热议问题