On Tue, Jul 11, 2017 at 7:24 PM, Alan Gauld via Tutor <[email protected]> wrote: > On 11/07/17 15:47, Jia Yue Kee wrote: >> I am new to Python and I came across the Python __del__ method > > The __del__() method is a bit of an oddity and often not > used in industrial strength Python code. > >> if __name__ == "__main__": >> x = Robot("Tik-Tok") >> y = Robot("Jenkins") >> z = x >> del x >> del z >> del y >> > >> My question being why is that "Robot has been destroyed" >> is only printed once in Case 2 > > Because __del__() only got called once. > Which is really quite good, although you don't know which > object's del() was called! > > The problem is that python does not promise to > call __del__() even when it is defined! It only promises > not to call it until all references are deleted. > So we can say when __del__() will not be called but > not when it will be called, if ever. The problem is > that __del__() is called by the garbage collector > when it actually collects the deleted object and that > could be a long time after the reference count goes > to zero, or possibly even never! > > This means __del__() is of limited usefulness since > you can't rely on it being called. So you can't safely > use it as a destructor to release resources. > >> ...after the del x and del z statements, the refcount >> to the Robot object should reach zero and subsequently >> triggers the __del__ method right? > > Nearly. > It *might* trigger the __del__() method, eventually. > Or it might not, there is no guarantee. Mostly it > will get called, but you can't count on it. >
I am assuming that when the OP ran his code from a file, that upon the script's completion, both object instances were garbage collected. Surely upon program completion, everything _is_ garbage collected? > I confess I don't fully understand the reasons why > it's been done that way, it just is... Now you have me wondering why, too! ~(:>)) boB _______________________________________________ Tutor maillist - [email protected] To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
