【问题标题】:The __str__ method returning a unicode string works in one environment but fails in another返回 unicode 字符串的 __str__ 方法在一种环境中有效,但在另一种环境中失败
【发布时间】:2012-10-01 06:44:57
【问题描述】:

我想,我了解 unicode 和 python。但是这个问题让我很困惑。 看看这个小测试程序:

# -*- coding: utf-8 -*-

class TestC(object):

    def __str__(self):
        return u'äöü'

import sys
print sys.version
print sys.stdin.encoding
print sys.stdout.encoding    
print u'öäü' #this works
x = TestC()
print x #this doesn't always work

当我从 ubuntu 上的 bash 终端运行它时,我得到以下结果:

2.7.3 (default, Aug  1 2012, 05:14:39) 
[GCC 4.6.3]
utf-8
utf-8
öäü
Traceback (most recent call last):
  File "test_mod.py", line 14, in <module>
    print x #this doesn't '
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)

但是,当我在 Eclipse 中运行相同的东西(使用 pydev 模块)时,两个打印语句都可以完美运行。控制台窗口说:

2.7.3 (default, Aug  1 2012, 05:14:39) 
[GCC 4.6.3]
utf-8
utf-8
öäü
äöü

有人可以向我解释一下问题是什么吗?为什么 __str__ 方法在一种情况下有效,而在另一种情况下无效?解决此问题的最佳方法是什么?

【问题讨论】:

  • 为什么要从 __str__ 函数返回 unicode?​​span>
  • 正如 Edward 所指出的,返回我的 unicode 字符串的正确位置可能是 _unicode_ 方法。但我仍然想知道:为什么 wrong 代码在我的 eclipse 环境中工作(这似乎是相同的)?

标签: python


【解决方案1】:

查看这个相关问题:Python __str__ versus __unicode__

基本上,您可能应该实现特殊方法__unicode__ 而不是__str__,并添加一个调用__unicode__ 的存根__str__

def __str__(self):
    return unicode(self).encode('utf-8')

【讨论】:

  • 非常感谢。但是您是否知道为什么它在一种情况下有效但在另一种情况下失败?
  • 这将在 Python 3 上失败,其中 __str__ 预计返回的不是字节,而是一个 Unicode 对象。
猜你喜欢
  • 1970-01-01
  • 2019-04-06
  • 1970-01-01
  • 2017-10-23
  • 1970-01-01
  • 1970-01-01
  • 2015-08-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多