只是想知道在__str__
方法中显示下一个节点的正确方法是什么。请参阅以下代码和结果。看起来有一些内置的递归性质链接了列表中每个节点的__str__
方法。谁能解释为什么以及如何让它正常运行,就像只打印下一个节点的地址一样。谢谢。
class Node(object):
def __init__(self, x):
self.val = x
self.next = None
def __str__(self):
return "Node {}, next is {}".format(self.val, self.next)
a = Node(1)
b = Node(2)
c = Node(3)
a.next = b
b.next = c
print(a)
Node 1, next is Node 2, next is Node 3, next is None
不要
打印self.next
的str
表示形式,而是尝试打印其repr
:
return "Node {}, next is {!r}".format(self.val, self.next)
结果:
Node 1, next is <__main__.Node object at 0x7f9f10066630>
打印所有节点的原因是 .format 在连接之前将每个输入转换为字符串。为此,它调用下一个节点的 __str__
方法,循环继续。
有两种选择可以让它按照您想要的方式运行。在__str__
方法中,您可以调用 __repr__
、 !r
,也可以使用 id 手动获取内存位置并按照您想要的任何方式格式化它。
return "Node {}, next is {!r}".format(self.val, self.next)
# or
return "Node {}, next is <__main__.Node object at {}>".format(self.val, hex(id(self.next)))
这两者都会产生相同的输出:
Node 1, next is <__main__.Node object at 0x1005d7fd0>