Thinking in Python: Difference between __str__ and __repr__ in Python
Thinking in Python: Difference between __str__ and __repr__ in Python
- 区别
- 网友的一些回答
区别
repr 和 str 的区别在于,后者是在 str() 函数被使用,或是在用 print 函数
打印一个对象的时候才被调用的,并且它返回的字符串对终端用户更友好。
如果你只想实现这两个特殊方法中的一个,repr 是更好的选择,因为如果一个对象
没有 str 函数,而 Python 又需要调用它的时候,解释器会用 repr 作为替代。
网友的一些回答
trthhrtz:
repr is used everywhere, except by print and str when a __str__is defined
Alex Martelli:
Unless you specifically act to ensure otherwise, most classes don’t have helpful results for either:
As you see – no difference, and no info beyond the class and object’s id. If you only override one of the two…:
as you see, if you override repr, that’s ALSO used for str, but not vice versa.
Other crucial tidbits to know: str on a built-on container uses the repr, NOT the str, for the items it contains. And, despite the words on the subject found in typical docs, hardly anybody bothers making the repr of objects be a string that eval may use to build an equal object (it’s just too hard, AND not knowing how the relevant module was actually imported makes it actually flat out impossible).
So, my advice: focus on making str reasonably human-readable, and repr as unambiguous as you possibly can, even if that interferes with the fuzzy unattainable goal of making repr’s returned value acceptable as input to eval!
Mickey Perlstein:
str is like toString. created so you can print the data repr is like serialize, or pickle. How do i recreate this object if i need to do so using eval()
还没有评论,来说两句吧...