Search code examples
pythonclasspython-3.xclass-variablesrepresentation

String representation of a class in Python 3


I'd like my classes to have a string representation which is based on a class variable (which may be different in derived classes). This answer suggests that metaclasses might be the way to go:

class MC(type):
    def __repr__(self):
        return 'Wahaha!'

class C():
    __metaclass__ = MC

print(C)

But this doesn't work in Python 3, returning

<class '__main__.C'>

instead of Wahaha!. Can someone explain to me what changed between Python 2 and 3 and how to go about it in Python 3?


Solution

  • What changed is how the metaclass is declared in 3.x.

    class C(metaclass=MC):
        pass