Why this code execute True? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

Why this code execute True?

class Solo(): x=0 def __str__(self): self.x=self.x+1 return str(self.x) a=Solo() print(str(a)=='2') #ouput=True But I think it should be false.can anyone explain me.

26th Mar 2018, 10:09 AM
Maninder $ingh
Maninder $ingh - avatar
3 Answers
0
I think that the first assignement for the variable a will store the value 1 so a = Solo() --> a = 1 When you call a with print function ,you call it twice so a = 2 and that output True Call it more then will give False!
26th Mar 2018, 10:58 AM
HBhZ_C
HBhZ_C - avatar
0
class Solo(): x=0 def __str__(self): self.x=self.x+1 return str(self.x) a=Solo() print (help(a.__str__)) print (str(a)) print(str(a)=='2') #ouput=True
17th May 2018, 4:19 PM
$ยข๐Žโ‚น๐”ญ!๐จ๐“
$ยข๐Žโ‚น๐”ญ!๐จ๐“ - avatar
0
__str__ is constructor for str method so when ever you call str method constructor is getting called. here when you instantiated a becAME 1 and when you called str a became 2. for checking you can multiple print (str(a)) lines.
17th May 2018, 4:22 PM
$ยข๐Žโ‚น๐”ญ!๐จ๐“
$ยข๐Žโ‚น๐”ญ!๐จ๐“ - avatar