+ 5
__del__ method in python
When is this method called? In the python course named Object's lifecycle there is written that the __del__ method of an object is called on 'del instance' statement. But other sources (python reference manual included if I am not mistaken) say that 'del' statement only decreases the reference number of an object and only when garbage collector decides that it needs more space and actually deletes the object, the __del__ method is called. That is important when working with resources that could have been deallocated sooner since there is no rule that gc needs to follow on the order of deallocation.
5 Réponses
0
__del__ method just decreases the reference count of the object of a class by 1 and deletes the object when the reference count is reduced to zero. this method is called when you try to delete the object of a class(if 'x' is the object then for calling __del__method we write "del x" this will reduce the ref. count of x by 1)
hope this may help
0
I am sorry but your answer is somehow confusing. I take it that
del statement decreases number of references and __del__ method is called when GC actually deletes the object instance.
0
__del__method is called everytime the del statement is issued(and decreases the ref count by 1 each time it is called)
0
I am sorry but that just does not seem right since my python code does not behave like that. It really seems that the del call only decreases the reference count and does not call anything. And the __del__ is called by GC later on...
>>> class A:
... def __init__(self):
... print('born')
... def __del__(self):
... print('died')
...
>>> a = A()
born
>>> b = a
>>> del a
>>> del b
died
Hope I rewrote that correctly...
0
__del__