【问题标题】:Python: __str__, but for a class, not an instance?Python:__str__,但是对于一个类,而不是一个实例?
【发布时间】:2012-03-02 01:36:06
【问题描述】:

我了解以下 Python 代码:

>>> class A(object):
...     def __str__(self):
...         return "An instance of the class A"
... 
>>> 
>>> a = A()
>>> print a
An instance of the class A

现在,我想更改

的输出
>>> print A
<class '__main__.A'>

我需要重载哪个函数才能做到这一点?即使该类从未实例化,该解决方案也必须有效。 Python 2.x 和 3 的情况是否不同?

【问题讨论】:

标签: python string class


【解决方案1】:

在元类上定义__str__()

class A(object):
    class __metaclass__(type):
        def __str__(self):
            return "plonk"

现在,print A 将打印 plonk

编辑:正如 jsbueno 在 cmets 中所指出的,在 Python 3.x 中,您需要执行以下操作:

class Meta(type):
    def __str__(self):
        return "plonk"
class A(metaclass=Meta):
    pass

即使在 Python 2.x 中,在类主体之外定义元类可能是一个更好的主意——我选择了上面的嵌套形式来节省一些输入。

【讨论】:

  • 当 OP 询问 Python 3 兼容性时,应该注意 Python 3 不支持这种分配元类的形式,因为“元类”的传递就像它在类声明中的关键字参数一样. (因此,必须在类主体之前定义元类)
  • @jsbueno:谢谢,错过了这个问题。
  • 你在回答之前有checked重复吗?
  • @PiotrDobrogost:我认为在回答之前我不必进行全面搜索。我会在一个问题之前这样做,但如果我回答的时间比搜索重复的时间少,我只会回答。
  • @PiotrDobrogost:对于提出问题的人来说,量身定制的答案通常更有用。在这种情况下,您链接到的问题不包含有关如何在 Python 3 中使用元类的信息。(我也经常将问题标记为重复。)
【解决方案2】:

在您的元类上定义__repr__ 方法:

class MetaClass(type):

    def __repr__(self):
          return "Customized string"

class TestClass(object):
   __metaclass__  = MetaClass


print TestClass # Customized string

【讨论】:

    猜你喜欢
    • 2016-01-21
    • 2013-04-01
    • 1970-01-01
    • 2012-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-19
    • 2012-08-14
    相关资源
    最近更新 更多