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?
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With