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.
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__
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With