+ 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 :)

7th Feb 2019, 11:41 AM
Ajeya Bhat
Ajeya Bhat - avatar
3 Answers
+ 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).
7th Feb 2019, 1:25 PM
Anna
Anna - avatar
+ 6
Yes
7th Feb 2019, 1:28 PM
Anna
Anna - avatar
0
Just to confirm, now there will be one instance of both a and b right?
7th Feb 2019, 1:27 PM
Ajeya Bhat
Ajeya Bhat - avatar