python2 输出问题

2018-07-09 22:42:19 +08:00
 FarewellRain
Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:22:17) [MSC v.1500 32
tel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 123456789.123456
>>> a
123456789.123456
>>> print(a)
123456789.123
>>>

请问为什么直接打印变量和 print 变量不一样
1634 次点击
所在节点    Python
3 条回复
JHerschel
2018-07-09 23:27:04 +08:00
直接打印是调用 a 对象的 __repr__() 方法,print(a) 是调用 a 对象的 __str__() 方法。

这两个方法的具体实现可以看这里啦:

http://svn.python.org/projects/python/trunk/Objects/floatobject.c

搜索 " PyOS_double_to_string() "。
NobodyVe2x
2018-07-11 11:16:37 +08:00
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 123456789.123456
>>> a
123456789.123456
>>> print(a)
123456789.123456
careofzm
2018-07-17 00:30:25 +08:00
这个东西尝试看了一原码
```
def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass
```
根据注释我们可以看出,返回的是 repr(self)
于是我们在去找找 repr 方法
```
def repr(obj): # real signature unknown; restored from __doc__
"""
Return the canonical string representation of the object.

For many object types, including most builtins, eval(repr(obj)) == obj.
"""
pass
```
翻译大致是说:
返回对象的规范字符串表示形式。
对于许多对象类型,包括大多数内置函数,eval(repr(obj))== obj

所以我尝试使用 repr 和 str
```
>>> a = 123456789.123456
>>> repr(a)
'123456789.123456'
>>> str(a)
'123456789.123'
···
再看看控制台输出
···
>>> a
123456789.123456
>>> print a
123456789.123
···
然后我们在使用 eval
···
>>> eval(repr(a))
123456789.123456
>>> eval(str(a))
123456789.123
```
这样大致上可以断定控制台上
普通显示:
a 相当于 eval(repr(a))
print a 相当于 eval(str(a))

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/469413

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX