首页 > 解决方案 > 实例的默认 __str__ 方法

问题描述

我有一个没有strorrepr方法的类。当我称之为:

>>> from ingest.tpr import TPR
>>> t=TPR()
>>> t # that is, "repr(t)"
<ingest.tpr.TPR instance at 0x101eb8518>

这里的默认表示似乎是这样的:

"<${path_to_class} instance at ${memory_address}>"

这个默认实现在哪里提供?上面是__repr__方法还是__str__方法——我知道它调用了__repr__上面的方法,但是方法__str____repr__方法在开始时都初始化为相同的东西,还是简单地将另一个称为“后备” . 换句话说,python 中的默认值__str____repr__外观是什么样的,在哪里定义?

标签: pythoncpython

解决方案


t.__repr__(这就是repr(t)所谓的)解析为(假设没有其他上游定义)object.__repr__,这是由 Python 实现定义的(例如,https://github.com/python/cpython/blob/master/Objects/typeobject.c#L3827 )


推荐阅读