如何修复我的链表代码显示:属性错误:"linked_list"对象没有属性"head"



我正在学习创建空链表的教程,但遇到了一个我不理解的错误。我是python中类的新手,所以当我运行代码时,不明白它说对象没有属性头是什么意思

class node:
def _init_(self,data=None):
self.data=data
self.next=None
class linked_list:
def _init_(self):
self.head = node()
def append(self,data):
new_node = node(data)
cur = self.head
while cur.next!=None:
cur = cur.next
cur.next = new_node
def length(self):
cur = self.head
total = 0
while cur.next!=None:
total+=1
cur = cur.next
return total
def display(self):
elems = []
cur_node = self.head
while cur_node.next!=None:
cur_node=cur_node.next
elems.append(cur_node.data)
print (elems)
my_list = linked_list()
my_list.display()

构造函数的名称不正确:它应该是__init__(2个下划线(而不是_init_

class linked_list:
def __init__(self):
self.head = node()

Python认为_init_只是另一个方法,而不是构造函数。因此,self.head的分配从未发生。

最新更新