+ 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 Antworten
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