Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 528
xnx Avatar asked Aug 08 '26 15:08

xnx


1 Answers

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

class C(metaclass=MC):
    pass
like image 62
Ignacio Vazquez-Abrams Avatar answered Aug 11 '26 04:08

Ignacio Vazquez-Abrams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!