在内置数字类型的Python上,repr和str始终相同吗? [英] Are repr and str always identical on Pythons builtin numeric types?

查看:87
本文介绍了在内置数字类型的Python上,repr和str始终相同吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python的内置数字类型(intboolfloatcomplex)上,reprstr是否相同,或者是否存在(深奥的?)两种情况产生不同的结果?

Are repr and str identical on Pythons built-in numeric types (int, bool, float, and complex), or are there (esoteric?) situations where the two may yield different results?

有关SO的相关问题(例如)着重于如何实现__repr____str__以不同的方式返回字符串的不同值,但我在数字的实际实现中找不到任何内容.

Related questions on SO (such as this one) focus on how __repr__ and __str__ may be implemented differently, and return different values for strings, but I can't find anything on the actual implementation on numbers.

推荐答案

您有关此信息的主要来源是 http://hg.python.org/cpython/file/tip/Objects 例如,在boolobject.c中:

Your primary source of information on this is http://hg.python.org/cpython/file/tip/Objects For example, in boolobject.c:

PyTypeObject PyBool_Type = {
    ...stuff...

    bool_repr,                                  /* tp_repr */

    ...stuff...

    bool_repr,                                  /* tp_str */

是的,保证它们是相同的.

so yes, they're guaranteed to be the same.

对于浮点数,float_reprfloat_str不同,并且取决于sys.float_repr_style.

For floats, float_repr is different from float_str and depends on sys.float_repr_style.

这篇关于在内置数字类型的Python上,repr和str始终相同吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆