[Tutor] destroying classes [reference counting]

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Sun, 2 Dec 2001 15:39:38 -0800 (PST)


On Sun, 2 Dec 2001, dman wrote:

> The reason you can't destroy an object is an object should only be
> destroyed when it is impossible to use it anymore (that is, there are
> no more references to it).  As hinted above, C++ makes you, the
> prorgrammer, keep track and decide when the object should go away.
> Python is the opposite - it keeps track for you and destroys the
> object when you no longer have any references to it.

As a side note: Python even allows us to see the reference count of an
object in Python if we use the sys.getrefcount() function:

###
from sys import getrefcount

def test():
    ref = getrefcount  ## I just want to make it easier to type.
    x = "some object"
    print ref(x)
    y = x
    print ref(x)
    z = x
    print ref(x)
    del y
    print ref(x)
###

When we run test(), we can see that the reference count of an object
increments every time we assign a new variable name for it:

###
>>> test()
3
4
5
4
###

Note that test() doesn't start at 1 because the very act of calling
getrefcount() on an object adds a few more references to that object!  


Hope this helps!