How do I change the string representation of a Python class?

198,656

Solution 1

The closest equivalent to Java's toString is to implement __str__ for your class. Put this in your class definition:

def __str__(self):
     return "foo"

You may also want to implement __repr__ to aid in debugging.

See here for more information:

Solution 2

This is not as easy as it seems, some core library functions don't work when only str is overwritten (checked with Python 2.7), see this thread for examples How to make a class JSON serializable Also, try this

import json

class A(unicode):
    def __str__(self):
        return 'a'
    def __unicode__(self):
        return u'a'
    def __repr__(self):
        return 'a'

a = A()
json.dumps(a)

produces

'""'

and not

'"a"'

as would be expected.

EDIT: answering mchicago's comment:

unicode does not have any attributes -- it is an immutable string, the value of which is hidden and not available from high-level Python code. The json module uses re for generating the string representation which seems to have access to this internal attribute. Here's a simple example to justify this:

b = A('b') print b

produces

'a'

while

json.dumps({'b': b})

produces

{"b": "b"}

so you see that the internal representation is used by some native libraries, probably for performance reasons.

See also this for more details: http://www.laurentluce.com/posts/python-string-objects-implementation/

Share:
198,656

Related videos on Youtube

snakile
Author by

snakile

Updated on November 07, 2020

Comments

  • snakile
    snakile over 3 years

    In Java, I can override the toString() method of my class. Then Java's print function prints the string representation of the object defined by its toString(). Is there a Python equivalent to Java's toString()?

    For example, I have a PlayCard class. I have an instance c of PlayCard. Now:

    >>> print(c)
    <__main__.Card object at 0x01FD5D30>
    

    But what I want is something like:

    >>> print(c)
    A♣
    

    How do I customize the string representation of my class instances?

    I'm using Python 3.x

  • Admin
    Admin over 13 years
    Wow, that's a pretty old version of the docs ;) s/release\/2.5.2\//
  • Senthil Kumaran
    Senthil Kumaran over 13 years
    The OP said that he is using python 3. Sub-classing object is not required.
  • mchicago
    mchicago about 10 years
    I dont think any output of 'a' would be expected. Json serialisation dosn't look at functions but at attributes and the class A dosn't contain any attributes, just three functions. Json dumps treats the object as a dictionary, and will convert all keys to strs.
  • Alvaro Silvino
    Alvaro Silvino about 8 years
    Dude repr resolve
  • Jeppe
    Jeppe almost 3 years
    I'm not quite sure why you're mixing "to string" and json.dumps which are two completely different things.