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:
- del reduces the reference count to an object by one
- __del__ executes when the reference count to an object is zero
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
__del__, that's called for you when the count goes to zero. You can calldelif you like, but just exiting the method where ObjectX and ListY are assigned will be enough to decrement the reference count to zero, so (usually) you don't need to calldel.