This question already has an answer here:
Can I define a __repr__
for a class rather than an instance? For example, I'm trying to do this
class A(object):
@classmethod
def __repr__(cls):
return 'My class %s' % cls
What I get is
In [58]: a=A()
In [59]: a
Out[59]: My class <class '__main__.A'>
In [60]: A
Out[60]: __main__.A
I'm trying to get the output of line 60 to look like "My Class A", not for the instance a. The reason I want to do this is I'm generating a lot of classes using Python's metaclass. And I want a more readable way to identify the class than the stock repr.
Sure, I demonstrate here, with a
__repr__
that passes therepr
test.And to demonstrate:
Either Python 2:
Or Python 3:
Or fairly universally:
And to do the
repr
test:What is the
repr
test? It's the above test from the documentation onrepr
:You need to define
__repr__
on the metaclass.__repr__
returns a representation of an instance of an object. So by defining__repr__
onA
, you're specifying what you wantrepr(A())
to look like.To define the representation of the class, you need to define how an instance of
type
is represented. In this case, replacetype
with a custom metaclass with__repr__
defined as you need.If you want to define a custom
__repr__
for each class, I'm not sure there's a particularly clean way to do it. But you could do something like this.Then you can customize on a per-class basis.