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

Björn Pollex picture Björn Pollex · Feb 8, 2011 · Viewed 213k times · Source

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?

Answer

Ignacio Vazquez-Abrams picture Ignacio Vazquez-Abrams · Feb 8, 2011

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.