+ 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.
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!
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
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.