简体   繁体   English

如何为类定义 __str__ 方法?

[英]How to define a __str__ method for a class?

In Python, the object class serves as the root superclass for all the (new-style) classes.在 Python 中, object类充当所有(新式)类的根超类。 By default at least, applying str and repr to the "class instance" of any subclass of object produces the same result:至少默认情况下,将strrepr应用于object的任何子类的“类实例”会产生相同的结果:

>>> 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:我想定义object一个子类,比如fancyobject ,它在各方面都与object相同,除了将strrepr应用于fancyobject本身会产生不同的输出:

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

Is there a way to do this in Python?有没有办法在 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. PS:我知道__str__特殊方法,但我的理解是,如果类A覆盖了__str__ ,那么只有在A实例上调用str才会调用覆盖方法,而不是在A本身上调用它时。 Ie: IE:

>>> 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".类型本身就是对象,因此通过对其类型调用__str__()方法将它们转换为字符串,该方法称为“元类”。 So you have to overwrite the __str__() method on the metaclass:所以你必须覆盖元类上的__str__()方法:

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

prints印刷

ham

You can also set the default metaclass for a whole module like this您还可以像这样为整个模块设置默认元类

class fancytype(type):
    def __str__(self):
        return self.__name__

__metaclass__ = fancytype

class ham:
    pass
print ham

Here's the new answer for Python 3. Basically, you pass in a metaclass as a keyword parameter to the class definition.这是 Python 3 的新答案。基本上,您将元类作为关键字参数传递给类定义。

class fancytype(type):
    def __str__(self):
        return self.__name__
class ham(metaclass=fancytype):
    pass
print(ham)

prints印刷

ham

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

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