实例的默认__str__方法 [英] Default __str__ method for an instance
问题描述
我有一个没有 str
或 repr
方法的类。而当我称呼它时:
I have a class without a str
or repr
method. And when I call it:
>>> from ingest.tpr import TPR
>>> t=TPR()
>>> t # that is, "repr(t)"
<ingest.tpr.TPR instance at 0x101eb8518>
此处的默认表示类似于:
The default representation here seems to be something like:
"<${path_to_class} instance at ${memory_address}>"
在哪里提供此默认实现?上面是 __ repr __
方法还是 __ str __
方法-我知道它称为上面的__repr __
方法,但 __ str __
和 __ repr __
方法都初始化为一开始是相同的事情,还是只是简单地将另一个称为后备。换句话说,默认的 __ str __
和 __ repr __
在python中是什么样子?在哪里定义?
Where is this default implementation supplied? And is the above the __repr__
method or the __str__
method -- I know it calls the __repr__
method in the above, but are both the __str__
and __repr__
methods initialized to the same thing at the start, or does one simply call the other as a "fall-back". In other words, what does the default __str__
and __repr__
look like in python and where would that be defined?
推荐答案
t .__ repr __
(这是 repr (t)
调用)解析为(假设没有其他上游定义) object .__ repr __
,该对象由Python实现定义(例如,< a href = https://github.com/python/cpython/blob/master/Objects/typeobject.c#L3827 rel = nofollow noreferrer> https://github.com/python/cpython/blob/master /Objects/typeobject.c#L3827 )
t.__repr__
(which is what repr(t)
calls) resolves to (assuming no other upstream definitions) object.__repr__
, which is defined by the Python implementation (for example, https://github.com/python/cpython/blob/master/Objects/typeobject.c#L3827)
这篇关于实例的默认__str__方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!