【问题标题】:Change the string representation of a class itself [duplicate]更改类本身的字符串表示[重复]
【发布时间】:2017-04-21 23:04:37
【问题描述】:

让我举个例子:

class Test:
    def __repr__(self):
        return "hi"

这会更改 Test 类型的对象的字符串表示形式,但不会更改 Test 本身的字符串表示形式:

print(Test)
--> "<class 'Test'>"

是否也可以覆盖类本身的字符串表示形式?

【问题讨论】:

  • 有趣!我可以问你,你为什么需要这个?
  • 我玩弄从解析的 C 头文件生成的 ctypes.Structure 实例。很高兴看到生成的类型里面有什么。

标签: python


【解决方案1】:

你需要使用元类:

class Meta(type):
    def __repr__(self):
        return "hi"

class Test(metaclass=Meta):
    pass

print(Test)
>>> hi

__repr__ 方法适用于实例而非类。然而在python中,一个类本身就是元类type的一个“实例”。因此,如果您使用自定义 __repr__ 方法创建自定义元类,则使用您的元类创建的所有类都将使用您的 __repr__ 方法。

更多阅读meta classes

【讨论】:

    猜你喜欢
    • 2021-08-21
    • 2011-06-22
    • 2017-06-03
    • 1970-01-01
    • 1970-01-01
    • 2017-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多