' NoneType'对象没有属性' next'错误

时间:2015-03-10 19:08:09

标签: python

def display(self):
    temp=self.start
    print "list is\n"       
    while temp.next==None:
        print temp.data
        print "\t"
        temp=temp.next
    print temp.data
    print "\n"

1 个答案:

答案 0 :(得分:1)

您似乎正在处理链接列表。如果下一个节点 None,您应该仅在节点上循环:

while temp.next is not None:

由于您在temp.next==None为真时进行循环,因此最终将temp设置为None temp=temp.next。请注意,只有当您的链接列表只包含一个元素时才会发生这种情况。

您几乎肯定想在此处测试temp,并使用print ...,省略换行符print否则会写:

while temp is not None:
    print temp.data, '\t',
    temp = temp.next

通过这种方式,您可以将self.start设置为None以表示空链表,并且您不会跳过链接列表中的最后一个元素(将打印node.datanode.next设置为None

您应该使用isis not来测试None; Python程序中只有一个None对象(Python从不创建它的副本,它是一个单例)。虽然== None!= None可行,但最好使用is Noneis not None