python 2.2 question...

Paolo Invernizzi paoloinvernizzi at dmsware.com
Mon Sep 24 12:34:26 EDT 2001


I've wondering if there is a solution in 2.2 for this question... (or in 2.1
;)

I want a custom str rapresentation for a class object... something like

>>>class A(object): pass
>>>str(A)
<MyStrRapresentation of class A>

I think the best way to do this is with a class method, something like
>>>class A(object):
...    def __str__(klass):
...        return "MyStrRapresentation of class %s" % klass.__name__
...   __str__ = classmethod(__str__)
>>>A.__str__()
"MyStrRapresentation of class A"
>>>str(A)
'__main__.A'

I think it must pass for a metaclass, something like this

>>>MyMeta(object):
...    def __str__(self):
...        return "MyStrRapresentation of ??"
>>>class A(object):
...    __metaclass__=MyMeta
>>>str(A)
<MyStrRapresentation of ??>

that is quite fine, but cannot "fill it" with something usefull like ids or
so...

Any idea? Or better, someone can point me where I'm doing wrong?
Thanks in advance!

Paolo Invernizzi






More information about the Python-list mailing list