__unicode __()不返回字符串

时间:2011-12-24 11:33:02

标签: python

我在python中有以下类

class myTest:
    def __init__(self, str):
        self.str = str

    def __unicode__(self):
        return self.str

并在其他文件中实例化myTest以尝试unicode()方法

import myClass


c = myClass.myTest("hello world")

print c

作为打印输出我得到<myClass.myTest instance at 0x0235C8A0>但是如果我覆盖 __ str __ ()我会得到hello world作为输出。我的问题是,如果我想要输出字符串,我应该如何编写 __ unicode __ ()的覆盖?

2 个答案:

答案 0 :(得分:13)

通常它是这样做的:

class myTest:
    def __init__(self, str):
        self.str = str

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

这是因为__unicode__并非以__str____repr__的方式隐式调用unicode。内置函数__str__在引擎盖下调用 ,因此如果您没有定义print unicode(c) ,则必须执行此操作:

{{1}}

答案 1 :(得分:1)

当您使用print时,Python会在您的班级中查找__str__方法。如果找到一个,它会调用它。如果没有,它将查找__repr__方法并调用它。如果找不到,则会创建对象的内部表示,

由于您的类没有定义__str__ __repr__,因此Python会创建自己的对象字符串表示形式。这就是print c显示<myClass.myTest instance at 0x0235C8A0>

的原因

现在,如果您想要调用__unicode__,则需要通过调用unicode built-in来请求对象的unicode版本:

unicode(c)

或强制将对象表示为unicode:

print u"%s" % c