[Tutor] Question about the object.__del__(self) method
Arup Rakshit
ar at zeit.io
Mon Apr 22 05:18:15 EDT 2019
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.
from python_methods import RandomKlass
obj = RandomKlass(10)
del obj
# Deleted...
obj = RandomKlass(10)
obj1 = RandomKlass(10)
del obj
# Deleted...
del obj1
# Deleted...
Now why then the doc https://docs.python.org/3/reference/datamodel.html#object.__del__ says:
> `del x` doesn’t directly call `x.__del__()` — the former decrements the reference count for `x` by one, and the latter is only called when `x`’s reference count reaches zero.
Also what the reference count here means? I know that x can hold only one reference at a time.
Thanks,
Arup Rakshit
ar at zeit.io
More information about the Tutor
mailing list