How to create a custom string representation for a class object?


Question

Consider this class:

class foo(object):
    pass

The default string representation looks something like this:

>>> str(foo)
"<class '__main__.foo'>"

How can I make this display a custom string?

1
176
6/9/2019 1:49:59 AM

Accepted Answer

Implement __str__() or __repr__() in the class's metaclass.

class MC(type):
  def __repr__(self):
    return 'Wahaha!'

class C(object):
  __metaclass__ = MC

print C

Use __str__ if you mean a readable stringification, use __repr__ for unambiguous representations.

241
12/17/2014 10:46:51 AM

class foo(object):
    def __str__(self):
        return "representation"
    def __unicode__(self):
        return u"representation"

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon