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

时间:2015-06-02 00:03:16

标签: python class python-3.x class-variables representation

我希望我的类有一个基于类变量的字符串表示(在派生类中可能有所不同)。 This answer表明元类可能是最佳选择:

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

class C():
    __metaclass__ = MC

print(C)

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

<class '__main__.C'>

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

1 个答案:

答案 0 :(得分:5)

在3.x中声明元类的方式发生了变化。

class C(metaclass=MC):
    pass
相关问题