如何添加默认的__str__
,以便在打印对象时输出类对象的典型输出以及自定义字符串?
class foo():
.
.
.
someObject = foo()
print(someObject)
>> <__main__.o object at 0x00000270E2C1E400> "Some additonal stuff"
答案 0 :(得分:2)
致电super().__str__()
获取默认值,然后添加所需的内容
>>> class Something(object):
... def __str__(self):
... return super().__str__() + "extra"
...
>>> s = Something()
>>>
>>> print(s)
<__main__.Something object at 0x7f976b5deeb8>extra
>>>