繁体   English   中英

__unicode __()不返回字符串

[英]__unicode__() doesn't return a string

我在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 __ ()的覆盖?

通常它是这样做的:

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)

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

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

现在,如果要调用__unicode__ ,则需要通过调用内置unicode来请求对象的unicode版本:

unicode(c)

或者通过强制将对象表示为unicode:

print u"%s" % c

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM