Python __str__与__unicode__ [英] Python __str__ versus __unicode__

查看:96
本文介绍了Python __str__与__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屋!

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