为何重写Node的__str__方法后,无需循环即可打印整个链表?
问题:为什么重写__str__后无需循环就能打印整个链表?
我正在创建链表,在Node和LinkedList两个类中都重写了__str__方法,目的是在控制台打印对象时能输出可读格式。但我发现调用print()函数时,无需循环就能打印出链表的所有元素,我推测是Node类__str__方法中的{self.next}导致了这种现象,但不清楚其工作原理。
代码如下:
class LinkedList: def __init__(self): self.head = None def __str__(self): if self.head is not None: return str(self.head) return 'empty linked list' def insert(self, data): if self.head is None: self.head = Node(data) else: head = self.head while head.next is not None: head = head.next head.next = Node(data) class Node: def __init__(self, data): self.data = data self.next = None def __str__(self): return f"{self.data}\n{self.next}" elems1 = [1,2,3,4] llist1 = LinkedList() for elem in elems1: llist1.insert(elem) print(llist1)
解答
你的推测完全正确,核心是Node类的__str__方法通过隐式递归完成了整个链表的遍历,具体流程拆解:
- print的底层逻辑:调用
print(llist1)时,Python会自动调用LinkedList类的__str__方法。这个方法里,当链表不为空时,会返回str(self.head)——也就是把链表的头节点转换成字符串。 - Node的__str__触发递归:头节点的
__str__方法返回f"{self.data}\n{self.next}",这里的关键是{self.next}:- 当
self.next是一个Node对象时,Python会自动调用这个Node对象的__str__方法,把它转换成字符串; - 这个过程会一层一层传递下去:节点1的
next是节点2,触发节点2的__str__;节点2的next是节点3,触发节点3的__str__……直到最后一个节点的next是None。
- 当
- 递归终止条件:
None转换成字符串是'None',不会再触发任何__str__调用,递归到此结束。
拿你的链表1->2->3->4->None举例,最终拼接出来的字符串是:
1 2 3 4 None
相当于__str__的递归调用替你完成了原本需要手动写循环的遍历工作,所以不用额外写循环就能打印全部元素。
内容的提问来源于stack exchange,提问作者Bishnu Chalise
相关产品推荐
相关产品推荐

