Changing the repr() of a class?
Alex Martelli
aleax at aleax.it
Thu Apr 18 15:27:36 EDT 2002
Donald McCarthy wrote:
> I would like to alter the way python displays what a class is. I can do
> this for an instance of a class using __repr__ but I don't know how to do
> this for a class.
You do it by defining a custom metaclass. Python 2.2 of course:
class FunkyReprMeta(type):
def __repr__(cls):
return "My wonderful class %s" % cls.__name__
class FunkyReprObject:
__metaclass__ = FunkyReprMeta
class C(FunkyReprObject):
"whatever you want here"
print C
this emits "My wonderful class C" and has otherwise just the semantics
of newstyle classes. A class is an instance of its metaclass, after all, so
that's how you define how/what happens when a class object gets
printed, added to something, etc -- define special methods in its
metaclass. Instead of deriving from FunkyReprObject, by the way,
you may prefer to define __metaclass__ in the class-body of C directly,
or as a module-level global variable.
Alex
More information about the Python-list
mailing list