Taking out the Trash the Garbage Collector

Python doesn't require you to explicitly allocate and free memory. When you need more memory to hold some data, the Python interpreter allocates it for you. When you are finished with data, the interpreter usually gets rid of it.

Python cleans up memory by using reference counting: For each chunk of memory you use, Python keeps track of how many references to the object exist. When you assign a reference to an object, its reference count increases; when you get rid of a reference, the object's reference count decreases. When there are no more references to an object, Python frees the object's memory:

... print "Deleting:",self.Name

>>> A=Thingy("X") # The variable A holds only reference >>> A="Crunchy frog" # Refcount goes to 0 -> object is freed!

Deleting: X >>> A=Thingy("X") >>> B=Thingy("Y")

>>> A.ref=B # Y's Refcount goes from 1 to 2 >>> B=None # Y's Refcount goes from 2 to 1

>>> # This takes X's refcount to 0, so X is deleted. Deleting >>> # X takes Y's refcount to 0, so Y is deleted too:

Note that the built-in function del does not (necessarily) delete an object; it deletes a variable (and thus decrements the object's reference count):

>>> A=Thingy("X") >>> B=Thingy("Y") >>> A.ref=B

>>> del B # Variable B is gone, but object Y still exists

>>> A. ref.Name # See! Object Y is still there!

0 0

Post a comment