对 Python 列表中的 __str__ 感到困惑 [英] Confused about __str__ on list in Python
问题描述
我有 Java 背景,我知道 __str__
有点像 toString 的 Python 版本(虽然我确实意识到 Python 是较旧的语言).
Coming from a Java background, I understand that __str__
is something like a Python version of toString (while I do realize that Python is the older language).
因此,我定义了一个小类以及一个 __str__
方法,如下所示:
So, I have defined a little class along with an __str__
method as follows:
class Node:
def __init__(self, id):
self.id = id
self.neighbours = []
self.distance = 0
def __str__(self):
return str(self.id)
然后我创建了它的几个实例:
I then create a few instances of it:
uno = Node(1)
due = Node(2)
tri = Node(3)
qua = Node(4)
现在,尝试打印这些对象之一时的预期行为是它的关联值被打印.这也会发生.
Now, the expected behaviour when trying to print one of these objects is that it's associated value gets printed. This also happens.
print uno
收益
1
但是当我执行以下操作时:
But when I do the following:
uno.neighbours.append([[due, 4], [tri, 5]])
然后
print uno.neighbours
我明白
[[[<__main__.Node instance at 0x00000000023A6C48>, 4], [<__main__.Node instance at 0x00000000023A6D08>, 5]]]
我所期望的
[[2, 4], [3, 5]]
我错过了什么?我在做什么其他令人畏缩的事情?:)
What am I missing? And what otherwise cringe-worthy stuff am I doing? :)
推荐答案
Python 有两种不同的方式将对象转换为字符串:str()
和 repr()
.打印对象使用 str()
;打印包含对象的列表使用 str()
作为列表本身,但是 list.__str__()
的实现调用 repr()
个别项目.
Python has two different ways to convert an object to a string: str()
and repr()
. Printing an object uses str()
; printing a list containing an object uses str()
for the list itself, but the implementation of list.__str__()
calls repr()
for the individual items.
所以你也应该覆盖__repr__()
.一个简单的
So you should also overwrite __repr__()
. A simple
__repr__ = __str__
在类主体的末尾会起作用.
at the end of the class body will do the trick.
这篇关于对 Python 列表中的 __str__ 感到困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!