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?

Community
  • 1
  • 1
xnx
  • 24,509
  • 11
  • 70
  • 109
  • Side note: PEP 8 recommends using 4 spaces per indentation, not 2. As a general rule, doing the same thing as virtually everybody else makes life simpler. I did edit your question, so as to not make newcomers believe that it is a good idea to stray away from the standard recommendation. – Eric O. Lebigot Jun 02 '15 at 00:13

1 Answers1

5

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

class C(metaclass=MC):
    pass
Eric O. Lebigot
  • 91,433
  • 48
  • 218
  • 260
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358