1

Let me make an example:

class Test:
    def __repr__(self):
        return "hi"

This changes the string representation of objects of type Test, but not of Test itself:

print(Test)
--> "<class 'Test'>"

Is it possible to overwrite the string representation of the class itself too?

Stefan
  • 4,187
  • 1
  • 32
  • 38

1 Answers1

3

You need to use meta classes:

class Meta(type):
    def __repr__(self):
        return "hi"

class Test(metaclass=Meta):
    pass

print(Test)
>>> hi

The __repr__ method works on instances not on classes. However in python a class is itself an "instance" of a meta class type. So if you make a custom meta class with a custom __repr__ method, all classes that are created with your meta class will use your __repr__ method.

Some more reading on meta classes.

martin.macko.47
  • 888
  • 5
  • 9