V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
FarewellRain
V2EX  ›  Python

python2 输出问题

  •  
  •   FarewellRain · 2018-07-09 22:42:19 +08:00 · 1626 次点击
    这是一个创建于 2114 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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 条回复    2018-07-17 00:30:25 +08:00
    JHerschel
        1
    JHerschel  
       2018-07-09 23:27:04 +08:00   ❤️ 2
    直接打印是调用 a 对象的 __repr__() 方法,print(a) 是调用 a 对象的 __str__() 方法。

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

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

    搜索 " PyOS_double_to_string() "。
    NobodyVe2x
        2
    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
        3
    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))
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3266 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 12:37 · PVG 20:37 · LAX 05:37 · JFK 08:37
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.