推荐学习书目
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 · Jul 9, 2018 · 2418 views
    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
    JHerschel
        1
    JHerschel  
       Jul 9, 2018   ❤️ 2
    直接打印是调用 a 对象的 __repr__() 方法,print(a) 是调用 a 对象的 __str__() 方法。

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

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

    搜索 " PyOS_double_to_string() "。
    NobodyVe2x
        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
    careofzm
        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))
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2877 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 50ms · UTC 11:01 · PVG 19:01 · LAX 04:01 · JFK 07:01
    ♥ Do have faith in what you're doing.