Python __str__ 与 __unicode__ [英] Python __str__ versus __unicode__
问题描述
对于何时应该实现 __str__()
与 __unicode__()
是否有 Python 约定.我已经看到类比 __str__()
更频繁地覆盖 __unicode__()
,但它似乎并不一致.什么时候实施一个比另一个更好,是否有特定的规则?两者都实施是否有必要/良好做法?
Is there a python convention for when you should implement __str__()
versus __unicode__()
. I've seen classes override __unicode__()
more frequently than __str__()
but it doesn't appear to be consistent. Are there specific rules when it is better to implement one versus the other? Is it necessary/good practice to implement both?
推荐答案
__str__()
是旧方法——它返回字节.__unicode__()
是新的首选方法——它返回字符.这些名称有点令人困惑,但在 2.x 中,出于兼容性原因,我们坚持使用它们.通常,您应该将所有字符串格式放在 __unicode__()
中,并创建一个存根 __str__()
方法:
__str__()
is the old method -- it returns bytes. __unicode__()
is the new, preferred method -- it returns characters. The names are a bit confusing, but in 2.x we're stuck with them for compatibility reasons. Generally, you should put all your string formatting in __unicode__()
, and create a stub __str__()
method:
def __str__(self):
return unicode(self).encode('utf-8')
在 3.0 中,str
包含字符,因此相同的方法被命名为 __bytes__()
和 __str__()
.这些行为符合预期.
In 3.0, str
contains characters, so the same methods are named __bytes__()
and __str__()
. These behave as expected.
这篇关于Python __str__ 与 __unicode__的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!