This topic created in 2868 days ago, the information mentioned may be changed or developed.
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 变量不一样
3 replies • 2018-07-17 00:30:25 +08:00
 |
|
2
NobodyVe2x Jul 11, 2018
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
|
 |
|
3
careofzm Jul 17, 2018
这个东西尝试看了一原码 ``` 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))
|