Reputation: 79
Python documentation said that an object is considered deleted if the reference counts to the object is zero and the difference between del and __del__ is that:
That means if we keep delete the reference to an object until the reference count to zero. It would executes __del__ to delete the object to free up memory.
However, what is troubling me is that:
If I create an object and bind the object to the name ObjectX. It would increase the reference count by 1, right?
If I create a list with the name ListY and I append the ListY with ObjectX. It means that it would increase the reference count to 2, right?
Now, if I delete ObjectX and ListY, would the reference count to the object is still remains as 1 and the object is still remaining sitting there in hard disk waiting for some kind soul to come and kill it?
Any comments and thoughts are welcomed....
By the way, if what is happening is really what I understand about deleting object in Python. Is there any good suggestion for how to delete an object that is appended into a list and free up the memory space?
class Slave:
def __init__(self):
self.name=""
def __del__(self):
print("SLAVE DEAD")
def sequence():
SlaveX=Slave()
slaveList=list()
slaveList.append(SlaveX)
del SlaveX
print("I AM NOT DEAD YET")
del slaveList
Upvotes: 6
Views: 16529
Reputation: 205
Imagine a simple class:
class Thingy:
pass
Now I can create an object of this class and call it george
:
george = Thingy()
Now I have created an instance of the class and I have one reference to it. Somewhere this count is maintained and set to 1.
I can make a new variable called mary
and assign it to the same object:
mary = george
Now I still only have one object, but I have two references to it. If I call methods on george
, this affects the object referred to by mary
because it's the same instance.
As you mention lists, let's add it to a list as well, but essentially it's exactly the same, it increases the reference count to 3.
my_objects = []
my_objects.append(george)
Now there are three references. Now, still inside this method, let's remove the references again
george = None # reference count drops to 2
mary = 3 # reference count drops to 1
my_objects.pop() # reference count drops to 0
when the count drops to 0, the python runtime realises this (maybe not straight away, but quickly enough) and calls the __del__
method on the instance. You don't care about this, you just let the references disappear.
Now, if I delete ObjectX and ListY, would the reference count to the object still remain as 1?
No, it would drop to zero.
and the object is still remaining sitting there in hard disk waiting for some kind soul to come and kill it?
No, it was only held in memory, and will be deleted and the memory freed again.
Upvotes: 10