Python 3中类的字符串表示形式

xnx*_*xnx 3 python class representation class-variables python-3.x

我希望我的类有一个基于类变量的字符串表示(在派生类中可能有所不同).这个答案表明,元类可能是要走的路:

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

class C():
    __metaclass__ = MC

print(C)
Run Code Online (Sandbox Code Playgroud)

但这在Python 3中不起作用,返回

<class '__main__.C'>
Run Code Online (Sandbox Code Playgroud)

而不是Wahaha!.有人可以向我解释Python 2和3之间的变化以及如何在Python 3中进行更改吗?

Ign*_*ams 5

更改的是在3.x中声明元类的方式.

class C(metaclass=MC):
    pass
Run Code Online (Sandbox Code Playgroud)