+ 1
Python question w.r.t init
Why is the output 122? class m(): n=0 def __init__(self): m.n+=1 def __del__(self): m.n-=1 a=m() print(a.n) b=m() print(b.n) a=m() print(a.n) Credit to Javier.I. Rivera R. for the question :)
3 Réponses
+ 7
n is a class variable. It isn't connected to the instances, but to the class. Each time a new class instance is created, __init__(self) is called and the counter is increased by one. Each time an instance is deleted, n is decreased by one, meaning that m.n effectively counts how many instances of m() exist. The variable a is declared twice, meaning that the former instance of m() is deleted and a new instance is created at the same moment. That's why the counter stays at 2 (instead of rising to 3).
+ 6
Yes
0
Just to confirm, now there will be one instance of both a and b right?