【发布时间】:2021-05-22 06:03:27
【问题描述】:
在这段代码中,类 Node 的对象正在使用一个未在任何地方定义的变量 next 并且代码仍在工作如何?对象如何使用未在其类中定义的变量
class Node:
def __init__(self, data):
self.data = data
class LinkedList:
# Function to initialize head
def __init__(self):
self.head = None
# Function to reverse the linked list
def reverse(self):
prev = None
current = self.head
while(current is not None):
next = current.next
current.next = prev
prev = current
current = next
self.head = prev
# Function to insert a new node at the beginning
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
# Utility function to print the linked LinkedList
def printList(self):
temp = self.head
while(temp):
print(temp.data)
temp = temp.next
llist = LinkedList()
llist.push(20)
llist.push(4)
llist.push(15)
llist.push(85)
print( "Given Linked List")
llist.printList()
llist.reverse()
print ("\nReversed Linked List")
llist.printList()
【问题讨论】:
-
“没有在任何地方定义” - 那么
new_node.next = self.head呢? -
是的,这是我的问题。对象可以只使用未在其自己的类中定义的变量吗?
-
new_node.next = ...没有“使用”任何东西,它在new_node实例上定义了一个next属性。看起来你可能会从阅读一个很好的关于类的基础教程中受益,这将帮助你澄清这些概念。 SO 并不是最好的地方。 -
是的,我只是一个初学者,所以仍在尝试解决问题,谢谢顺便说一句
标签: python python-3.x oop linked-list