Björn Pollex Björn Pollex - 1 year ago 88
Python Question

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

Consider this class:

class foo(object):

The default string representation looks something like this:

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

How can I make this display a custom string?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download