[英]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:至少默认情况下,将
str
和repr
应用于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
相同,除了将str
和repr
应用于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.