英文:
Print is printing elements of linked list without loop
问题
我正在创建链表。在我的链表中,我在Node和LinkedList两个类中都有__str__方法。我尝试的目标是,每当我将对象打印到控制台时,以可读格式打印对象。因此,我在Node类中使用了__str__方法,但我不知道为什么每当我使用print()函数时,它会在不使用任何循环的情况下打印链表中的所有元素。
我发现在Node类的__str__方法中使用{self.next}是导致这种行为的原因,但我不知道它是如何工作的。
英文:
I am creating linked list. In my linked list i have str method in both classes Node and LinkedList. What i was trying to do is, print object in readable format whenever i print object to console. So i used str method in Node class, but i have no idea how this is printing all elements in the linked list without any loop whenever i use print() function.
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)
I figured out that using {self.next} in str method in Node class is causing such behaviour but i have now idea how this is working.
答案1
得分: 1
print(llist1)调用方法LinkedList.__str__LinkedList.__str__方法然后调用str(self.head),然后调用方法Node.__str__Node.__str__方法返回表达式f"{self.data}\n{self.next}"- 在评估该表达式时,您必须调用
self.next然后将其字符串化。 (在该 f-string 中放置self.next表达式调用__str__方法) - 现在您已经在
self.next上调用了Node.__str__,我们知道这将继续调用 它的self.next依此类推,直到self.next == None为止,此时没有更多的__str__方法可供调用 self.next将返回空字符串 并停止递归调用栈
您已经创建了一个递归程序而没有意识到它。
英文:
Lets go down (or up if you prefer) the call stack.
print(llist1)this calls the methodLinkedList.__str__- that
LinkedList.__str__then callsstr(self.head)which then calls the methodNode.__str__ - that
Node.__str__then returns the expressionf"{self.data}\n{self.next}" - in evaluating that expression, you then must call the self.next and then stringifyit. (putting that expression
self.nextin that f-string calls the__str__method) - so now you've called
Node.__str__onself.nextwhich as we know will then call itsself.nextand so on and so on untilself.next == Nonein which case there's no more__str__method to call self.nextwill return the empty string and stop the recursive call stack
You've created a recursive program without realizing it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论