2017-04-11 57 views
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 

回答

1

我已經限制問題比較str(x)x.__str__()

在REPL(Python的2或Python 3):

>>> x = 0.123456789 
>>> print(str(x)) 
0.123456789 
>>> print(x.__str__()) 
0.123456789 

隨着IPython3:

In [2]: x = 0.123456789 
    ...: ...: print(str(x)) 
    ...: ...: print(x.__str__()) 
    ...: 
0.123456789 
0.123456789 

,但我得到了同樣的問題,你當我在Jupyter筆記本執行:

x = 0.123456789 
print(str(x)) 
print(x.__str__()) 

#0.123456789 
#0.12345679 

所以,這個問題似乎與Jupyter有關。但我還沒有找到更多有關它呢...

+0

好吧,但正確的輸出是0.12345679 –

相關問題