Why This Output? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
10th May 2021, 3:21 PM
Himanshu Kumar
Himanshu Kumar - avatar
4 Answers
+ 2
That's an interesting question. It is made clear with a few extra print statements. I ran the following modified version: class MyClass(): n = 0 def __init__(self): print('init called.') MyClass.n += 1 def __del__(self): print('del called.') MyClass.n -= 1 a = MyClass() print(a.n) b = MyClass() print(b.n) a = MyClass() print(a.n) That printed: init called. 1 init called. 2 init called. del called. 2 del called. del called. The property is static which is why all instances of MyClass are actually the same number. You probably knew this much, though. The more interesting question is why the 2 repeats even though the constructor is called 3 times. The answer is that a is being replaced and therefore the __del__ is also being called immediately. The combination of init(+1) and del(-1) causes no overall change to n and hence n remains 2 for the last print(a.n).
11th May 2021, 5:03 AM
Josh Greig
Josh Greig - avatar
+ 2
__del__ is called automatically when an object becomes unreferenced. It is to free up memory. It is like Python's version of a destructor. The variable "a" had a reference to one instance of MyClass. The second time a = MyClass() runs, the object a previously pointed at becomes unreferenced. The more official and more detailed explanation is at: https://docs.python.org/3/reference/datamodel.html#object.__del__
11th May 2021, 5:14 AM
Josh Greig
Josh Greig - avatar
+ 1
why __del__ called automatically?
11th May 2021, 5:06 AM
Himanshu Kumar
Himanshu Kumar - avatar
+ 1
Thanks Sir now i understand
11th May 2021, 5:40 AM
Himanshu Kumar
Himanshu Kumar - avatar