Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't __del__ work properly

Tags:

python

class

I think this is the most common question on interviews:

class A:
     def __init__(self, name):
          self.name = name
     def __del__(self):
          print self.name,

aa = [A(str(i)) for i in range(3)]
for a in aa:
    del a

And so what output of this code and why. Output will be is nothing and why? Thats because a is ref on object in list and then we call del method we remove this ref but not object?

like image 223
Denis Avatar asked Dec 18 '25 18:12

Denis


2 Answers

There are at least 2 references to the object that a references (variables are references to objects, they are not the objects themselves). There's the one reference inside the list, and then there's the reference "a". When you del a, you remove one reference (the variable a) but not the reference from inside the list.

Also note that Python doesn't guarantee that __del__ will ever be called ...

like image 99
mgilson Avatar answered Dec 21 '25 07:12

mgilson


__del__ gets called when an object is destroyed; this will happen after the last possible reference to the object is removed from the program's accessible memory. Depending on the implementation this might happen immediately or might be after some time.

Your code just removes the local name a from the execution scope; the object remains in the list so is still accessible. Try writing del aa[0], for example.

like image 27
ecatmur Avatar answered Dec 21 '25 06:12

ecatmur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!