简体   繁体   English

Python:__str__,但对于一个类,而不是一个实例?

[英]Python: __str__, but for a class, not an instance?

I understand the following Python code: 我理解以下Python代码:

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

Now, I would like to change the output of 现在,我想改变输出

>>> print A
<class '__main__.A'>

Which function do I need to overload to be able to do that? 我需要哪个函数来重载才能做到这一点? The solution has to work even if the class is never instantiated. 即使从未实例化类,解决方案也必须工作。 Is the situation different in Python 2.x and 3? Python 2.x和3中的情况有所不同吗?

Define __str__() on the metaclass: 在元类上定义__str__()

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

Now, print A will print plonk . 现在, print A将打印plonk

Edit : As noted by jsbueno in the comments, in Python 3.x you would need to do the following: 编辑 :正如jsbueno在评论中所述,在Python 3.x中,您需要执行以下操作:

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

Even in Python 2.x it might be a better idea to define the metaclass outside the class body -- I chose the nested form above to save some typing. 即使在Python 2.x中,在类体外部定义元类也是一个更好的主意 - 我选择上面的嵌套形式来保存一些输入。

Define the __repr__ method on your meta class: 在元类上定义__repr__方法:

class MetaClass(type):

    def __repr__(self):
          return "Customized string"

class TestClass(object):
   __metaclass__  = MetaClass


print TestClass # Customized string

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM