2011-12-24 93 views
7

我有蟒蛇下面的類__unicode __()不返回一個字符串

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 __()如果我想要它輸出字符串?

回答

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

當您使用print,Python會尋找在__str__方法你的班。如果它找到一個,它會調用它。如果沒有,它會查找__repr__方法並調用它。如果它找不到,它會創建一個對象的內部表示,因爲Python沒有定義__str__既不是__repr__,Python也會創建它自己的對象的字符串表示形式。這就是爲什麼print c顯示爲<myClass.myTest instance at 0x0235C8A0>

現在,如果你想__unicode__被調用,您需要,無論是通過調用unicode built-in要求你的對象的Unicode版本:

unicode(c) 

或迫使你的對象被表示爲Unicode:

print u"%s" % c