On 22/04/2019 10:18, Arup Rakshit wrote: > Consider the below in simple class: > > class RandomKlass: > def __init__(self, x): > self.x = x > > def __del__(self): > print("Deleted…") > > Now when I delete the object created from RandomKlass using `del` operator I > see the output “Deleted…”. That means `del` operator calls the __del__ method > if available.
No it doesn't, it just means that is what seemed to happen in this specific scenario. Now try: >>> from python_methods import RandomKlass >>> o1 = RandomKlass(10) >>> o2 = o1 >>> oblist = [o1,o2] >>> del(o1) >>> del(o2) >>> del(oblist) Deleted... So your __del__() is only called once, after all the references to the instance have been deleted. > Also what the reference count here means? > I know that x can hold only one reference at a time. Remember that variables in Python are just names that refer to objects. So, while the name 'x' can only refer to one object at a time, many other names can also refer to that same object, as in the example above. o1, o2 and oblist[0] and oblist[1] all refer to the same original instance of your class. Each time a new variable references the instance an internal "reference count" is incremented. When a referring name is deleted the reference count is decremented. Once the count reaches zero the instance is deleted and its __del__() method, if it exists, is called. So, only when all the names referring to the instance have been deleted is the __del__() method called. (And it is important to realise that there are cases where __del__() is never called. Do not rely on __del__() for any critical actions - such as saving instance data or shutting down the nuclear reactor.) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor