繁体   English   中英

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

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

我理解以下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中的情况有所不同吗?

在元类上定义__str__()

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

现在, print A将打印plonk

编辑 :正如jsbueno在评论中所述,在Python 3.x中,您需要执行以下操作:

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

即使在Python 2.x中,在类体外部定义元类也是一个更好的主意 - 我选择上面的嵌套形式来保存一些输入。

在元类上定义__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