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'>"
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…