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.
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
typeis represented. In this case, replacetypewith 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.