How to give object away to python garbage collection?

前端 未结 4 801
走了就别回头了
走了就别回头了 2020-12-18 23:43

There are several threads on Python garbage collection in SO, and after reading about five, plus some doc on line, i am still not sure as to how garbage collection works and

4条回答
  •  悲哀的现实
    2020-12-19 00:22

    Maybe this also can help:

    >>> # Create a simple object with a verbose __del__ to track gc.
    >>> class C:
    ...     def __del__(self):
    ...         print "delete object"
    ... 
    >>> c = C()
    >>> # Delete the object c successfully.
    >>> del c
    delete object
    >>> # Deletion of an object when it go out of the scope where it was defined.
    >>> def f():
    ...     c = C()
    ...
    >>> f()
    delete object
    >>> c = C()
    >>> # Create another reference of the object.
    >>> b = c
    >>> # The object wasn't destructed the call of del only decremented the object reference. 
    >>> del c
    >>> # Now the reference counter of the object reach 0 so the __del__ was called. 
    >>> del b
    delete object
    >>> # Create now a list that hold all the objects.
    >>> l = [C(), C()]
    >>> del l
    delete object
    delete object
    >>> # Create an object that have a cyclic reference.
    >>> class C:
    ...     def __init__(self):
    ...         self.x = self
    ...     def __del__(self):
    ...         print "delete object"
    ... 
    >>> c = C()
    >>> # Run the garbage collector to collect object.
    >>> gc.collect()
    9
    >>> # the gc.garbage contain object that the gc found unreachable and could not be freed.  
    >>> gc.garbage
    [<__main__.C instance at 0x7ff588d84368>]
    >>> # Break the cyclic reference.
    >>> c.x = None
    >>> # And now we can collect this object.
    >>> del c
    delete object
    >>> # Create another object with cyclic reference.
    >>> c = C()
    >>> # When closing the interactive python interpreter the object will be collected.
    delete object
    

    Refrences : del method ; gc module ; weakref module

提交回复
热议问题