Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I provide an informal string representation of a python Class (not instance)

Tags:

python

I understand how I can provide an informal representation of an instance of the object, but I am interested in providing an informal string representation of the Class name.

So specifically, I want to override what is returned when I print the Class (__main__.SomeClass).

>>> class SomeClass:
...   def __str__(self):
...     return 'I am a SomeClass instance.'
... 
>>> SomeClass
<class __main__.SomeClass at 0x2ba2f0fd3b30>
>>> print SomeClass
__main__.SomeClass
>>> 
>>> x = SomeClass()
>>> x
<__main__.SomeClass instance at 0x2ba2f0ff3f38>
>>> print x
I am a SomeClass instance.
like image 312
adam Avatar asked Aug 18 '11 15:08

adam


1 Answers

Your problem is called meta class confusion. Of class A, if A.__str__(self) is a template for methods of instances of A, how can I provide a method __str__() for A itself? Meta classes to the rescue.

The following links explain this better than I could here.

http://gnosis.cx/publish/programming/metaclass_1.html

http://gnosis.cx/publish/programming/metaclass_2.html

A short example here:

class AMeta(type):
    def __str__(self):
        return "I am the truly remarkable class A"

class A(object):
    __metaclass__ = AMeta
    def __str__(self):
        return "I am an A instance"

print A
I am the truly remarkable class A
print A()
I am an A instance

Btw you can do the same for __repr__.

like image 191
Jürgen Strobel Avatar answered Sep 24 '22 19:09

Jürgen Strobel