python - Python 3 中类的字符串表示

标签 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 中进行处理吗?

最佳答案

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

class C(metaclass=MC):
    pass

关于python - Python 3 中类的字符串表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30585295/

相关文章:

Python 在结束帖子编号处将点零添加到字符串

java - 当给定输入时调用不同类的包?

html - 重写输入类型时 CSS 中的 ID 或类?

python - 在 Python 中延迟转置列表

python-3.x - 按索引自然排序 Pandas 数据帧

python - 在 Python 的多处理库中获取队列的长度

Python "with"语句堆积

python - 通过使用另一个 numpy 数组作为掩码删除列来压缩 numpy 数组(矩阵)

python - 在 Python 中创建 HTTPS 代理服务器

swift - 泛型的泛型? A<T<U>> 类?