+ 3

The ouput of one python challenge

Though it looks like a very bad way to write the Python code, can anyone explain why the output is 122? https://code.sololearn.com/c4IR36w7t3Od/?ref=app

11th Jul 2017, 7:26 PM
S Liu
S Liu - avatar
2 Réponses
+ 8
n is a class variable. It is incremented each time a new object of this class is called and decremented when an object is deleted. First, the a object is called, so n gets upped by 1 and is printed. Then, b is created, so n increases to 2 and is printed. Then, a is reinitialized - so it is deleted (n-=1) and re-created again (n+=1). So n stays at net 2 and is again printed.
11th Jul 2017, 7:52 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
0
@ Kuba Siekierzynski, thank you for your answer. If we change MyPc in the object definition into self, the output is different again. May I ask what is the difference?
12th Jul 2017, 8:22 AM
S Liu
S Liu - avatar