在内置数字类型的Python上,repr和str始终相同吗? [英] Are repr and str always identical on Pythons builtin numeric types?
问题描述
在Python的内置数字类型(int
,bool
,float
和complex
)上,repr
和str
是否相同,或者是否存在(深奥的?)两种情况产生不同的结果?
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_repr
与float_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屋!