2
在下面的代碼,我不明白爲什麼x.__str__()
和str(x)
產生不同的結果:如何強制str(f)產生與f .__ str __()相同的輸出?
import gc
def mystr(self): return "{:.8f}".format(self)
underlying_dict = gc.get_referents(float.__dict__)[0]
underlying_dict["__repr__"] = mystr
underlying_dict["__str__"] = mystr
# I want to see 0.12345679
x = 0.123456789
print 1, "{:.8f}".format(x) # works
print 2, mystr(x) # works
print 3, x # fails
print 4, x.__str__() # works
print 5, x.__repr__() # works
print 6, str(x) # fails
print 7, type(x) # just checking the type
好吧,但正確的輸出是0.12345679 –