如何为类定义 __str__ 方法? [英] How to define a __str__ method for a class?

查看:85
本文介绍了如何为类定义 __str__ 方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中,object 类充当所有(新式)类的根超类.至少默认情况下,将 strrepr 应用于 object 的任何子类的类实例"会产生相同的结果:

<预><代码>>>>垃圾邮件类(对象):通过...>>>str(垃圾邮件)<class '__main__.spam'>">>>str(垃圾邮件) == repr(垃圾邮件)

我想定义一个 object 的子类,比如 fancyobject,它在各方面都与 object 相同,除了应用 strreprfancyobject 本身产生不同的输出:

<预><代码>>>>类火腿(花式对象):通过...>>>力量(火腿)'火腿'>>>代表(火腿)<class '__main__.ham'>"

有没有办法在 Python 中做到这一点?

PS:我知道 __str__ 特殊方法,但我的理解是如果 class A 覆盖 __str__,那么只有在 A 的实例上调用 str 时才会调用覆盖方法,而不是在 A 本身上调用它时.即:

<预><代码>>>>A类(对象):... def __str__(self):... return 'from new __str__: ' + object.__str__(self)...>>>str(A())'来自新的 __str__:<__main__.A 对象在 0x7f79c62a5310>'>>>字符串(A)<class '__main__.A'>"

解决方案

实际上与对象实例相同的机制适用于类型.类型本身就是对象,因此通过调用它们的 类型的__str__() 方法将它们转换为字符串,该方法称为元类".所以你必须覆盖元类上的 __str__() 方法:

classfancytype(type):def __str__(self):返回 self.__name__类火腿(对象):__metaclass__ = 花式类型打印火腿

印刷品

火腿

In Python, the object class serves as the root superclass for all the (new-style) classes. By default at least, applying str and repr to the "class instance" of any subclass of object produces the same result:

>>> class spam(object): pass
... 
>>> str(spam)
"<class '__main__.spam'>"
>>> str(spam) == repr(spam)

I would like to define a subclass of object, say fancyobject, that is identical to object in every way, except that applying str and repr to fancyobject itself produces different outputs:

>>> class ham(fancyobject): pass
...
>>> str(ham)
'ham'
>>> repr(ham)
"<class '__main__.ham'>"

Is there a way to do this in Python?

PS: I'm aware of the __str__ special method, but it is my understanding that if class A overrides __str__, then the overriding method is called only when str is called on instances of A, not when it is called on A itself. I.e.:

>>> class A(object):
...     def __str__(self):
...         return 'from new __str__: ' + object.__str__(self)
... 
>>> str(A())
'from new __str__: <__main__.A object at 0x7f79c62a5310>'
>>> str(A)
"<class '__main__.A'>"

解决方案

Actually the same mechanism as for object instances applies for types. Types are just objects themselves, so they are converted to strings by calling the __str__() method on their type, which is called the "metaclass". So you have to overwrite the __str__() method on the metaclass:

class fancytype(type):
    def __str__(self):
        return self.__name__
class ham(object):
    __metaclass__ = fancytype
print ham

prints

ham

这篇关于如何为类定义 __str__ 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆