【问题标题】:Default __str__ method for an instance实例的默认 __str__ 方法
【发布时间】:2019-10-10 03:25:50
【问题描述】:

我有一个没有strrepr 方法的类。当我调用它时:

>>> 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__ 方法在开始时都初始化为相同的东西,或者只是将另一个称为“后备”。换句话说,默认的__str____repr__ 在python 中是什么样子的,在哪里定义?

【问题讨论】:

    标签: python cpython


    【解决方案1】:

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

    【讨论】:

    • 谢谢——你能提供一个指向(任何版本的)python 的链接吗?另外,__str__ 是否有单独的定义,还是默认调用 __repr__。?
    • @user2357112 谢谢——哇,很多事情你在定义中永远不会想到(我认为它会是一行)。例如:/* It is possible for a type to have a tp_repr representation that loops infinitely. */ if (Py_EnterRecursiveCall(" while getting the repr of an object")) return NULL;
    • @chepner: PyObject_Reprrepr 的 C API 版本,而不是 object.__repr__object 实现位于 Objects/typeobject.c
    • @user2357112 你知道,我不止一次犯过这个错误。
    猜你喜欢
    • 1970-01-01
    • 2017-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多