Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

__unicode__() doesn't return a string

Tags:

python

I have the following class in python

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

    def __unicode__(self):
        return self.str

and in some other file a instantiate myTest to try out the unicode() method

import myClass


c = myClass.myTest("hello world")

print c

as print out I get <myClass.myTest instance at 0x0235C8A0> however if I overrider __str__() I will get hello world as output. My question is, how should I write the overrider for __unicode__() if I want it to output string instead?

like image 603
starcorn Avatar asked Dec 24 '11 11:12

starcorn


2 Answers

Generally it is done like this:

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

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

This is because __unicode__ is not called implicitly in they way that __str__ and __repr__ are. It is called under the hood by the built-in function unicode, so if you don't define __str__ you would have to do:

print unicode(c)
like image 149
manojlds Avatar answered Nov 16 '22 11:11

manojlds


When you use print, Python will look for an __str__ method in your class. If it finds one, it will call it. If it does not, it will look for a __repr__ method and call it. If it cannot find one, it will create an internal representation of your object,

Since you class does not define __str__ neither __repr__, then Python creates its own string representation of the object. This is why print c displays <myClass.myTest instance at 0x0235C8A0>.

Now, if you want __unicode__ to be called, you need to request a unicode version of your object, either by calling the unicode built-in:

unicode(c)

or by forcing your object to be represented as unicode:

print u"%s" % c
like image 25
Rodrigue Avatar answered Nov 16 '22 10:11

Rodrigue