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
  • 23,169
  • 9
  • 62
  • 102
  • 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
  • 86,421
  • 44
  • 210
  • 254
Ignacio Vazquez-Abrams
  • 740,318
  • 145
  • 1,296
  • 1,325