【发布时间】:2015-09-11 22:10:23
【问题描述】:
我收到一个 unicode 错误只有在覆盖我的类的__str__ 方法时。怎么回事?
在Test.py:
class Obj(object):
def __init__(self):
self.title = u'\u2018'
def __str__(self):
return self.title
print "1: ", Obj().title
print "2: ", str(Obj())
运行这个我得到:
$ python Test.py
1: ‘
2:
Traceback (most recent call last):
File "Test.py", line 11, in <module>
print "2: ", str(Obj())
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2018' in position 0: ordinal not in range(128)
编辑:请不要只说str(u'\u2018') 也会引发错误!(虽然这可能是相关的)。这绕过了内置方法重载的全部目的——这段代码在任何时候都不应该调用str(u'\u2018')!!
【问题讨论】:
-
str(Obj().title)具有相同的行为,它与__str__无关 -
afaik
__str__有合同义务返回 ascii 字节而不是 unicode,不这样做可能会导致问题...尝试def __str__(self):return self.title.encode("utf8") -
@DilithiumMatrix 事实是错误来自
title中的unicode,而不是因为__str__的重载,stackoverflow.com/help/mcve 会突出显示这一点,问题是重复的 -
@DilithiumMatrix 在重载方法中不会发生。
str(Obj())将调用str(Obj().__str__()),它变成str(u'\u2018')并抛出UnicodeEncodeError。我不明白你为什么对给你答案的人如此敌视。 -
你是敌对的,因为你对 Python 的工作原理知之甚少,却对帮助你的人大喊大叫,投反对票。祝你好运。