__unicode__() 不返回字符串

7 投票
2 回答
4044 浏览
提问于 2025-04-17 08:57

我在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 个回答

1

当你使用 print 时,Python 会在你的类里查找一个叫 __str__ 的方法。如果找到了,就会调用这个方法。如果没有找到,它会继续查找 __repr__ 方法并调用它。如果这两个方法都找不到,Python 就会自己生成一个对象的内部表示。

由于你的类里没有定义 __str____repr__,所以 Python 就自己创建了这个对象的字符串表示。这就是为什么当你执行 print c 时,会显示 <myClass.myTest instance at 0x0235C8A0> 的原因。

如果你想要调用 __unicode__ 方法,你需要请求对象的 unicode 版本,可以通过调用 unicode 内置函数 来实现:

unicode(c)

或者你也可以强制让你的对象以 unicode 形式表示:

print u"%s" % c
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)

撰写回答