+ 2

Working with __del__ deconstructor

I was just creating a class for practice and i overloaded the __del__ deconstructor to print "item was scrapped" whenever an instance is deleted. I made two instances of an object and ran the code and the deconstructor printed its message twice. My question is, Does the deconstructor run in the background for garbage collection silently and automatically usually? Because i didnt delete either instance and i got the deconstructor message still. I put just a random input statement after i made the two instances to put a pause on the script and check it out and boom. No deconstruct message. I think i get it, but i can't find anything online.

8th May 2020, 2:33 PM
Slick
Slick - avatar
2 Antworten
+ 1
The deconstructor happens after your object is not referred to anymore by anything in your code, which garbage collection handles. So neither do you need to use del, nor will del trigger it (when an instance still remains somewhere). When the reference count sinks to zero, then and only then can the object be 'marked for deletion'. If you don't manually get there in your code, they'll vanish into oblivion when the current interpreter session ends. I demonstrate this with different examples in my little tutorial about references: https://code.sololearn.com/c89ejW97QsTN/?ref=app
8th May 2020, 4:25 PM
HonFu
HonFu - avatar
+ 1
Thats it, appreciate that
8th May 2020, 4:35 PM
Slick
Slick - avatar