附加到默认的__str__输出实现

时间:2019-06-13 17:28:44

标签: python python-3.x printing

如何添加默认的__str__,以便在打印对象时输出类对象的典型输出以及自定义字符串?

class foo():
    .
    .
    .    

someObject = foo()
print(someObject)
>> <__main__.o object at 0x00000270E2C1E400> "Some additonal stuff"

1 个答案:

答案 0 :(得分:2)

致电super().__str__()获取默认值,然后添加所需的内容

>>> class Something(object):
...     def __str__(self):
...             return super().__str__() + "extra"
... 
>>> s = Something()
>>> 
>>> print(s)
<__main__.Something object at 0x7f976b5deeb8>extra
>>>