+ 2
Help me to solve the code #0001
#help in in this code i don't understand class MyClass(): n = 0 def __init__(self) : MyClass.n += 1 def __del__(self) : MyClass.n -= 1 a = MyClass() print(a.n) b = MyClass() print(b.n) a = MyClass() print(a.n) """ this code gives output 1 2 2 i don't understand how..? """
2 Answers
+ 3
line 11 : as the variable a is reassigned, the object created line 7 gets de-referenced so __del__ is called and n is decremented.
Then as a new object is created the __init__ function is called and n is incremented again.
+ 4
Before the second a = MyClass() goes and executes __init__, the existing a is deleted calling __del__.