首页 > 解决方案 > 属性访问在打印语句中有效,但在 while 循环中引发关于 NoneType 的 AttributeError

问题描述

我在某个对象上使用循环时收到“ AttributeError: 'NoneType' object has no attribute ”错误。while

我正在尝试在 Python 中实现一个链表。我曾print用于调试,它按预期输出一个值(不是None),但是在循环中使用此实例时出现错误。

delete功能:

    def delete(self , value):
        current = self.head
        #for debugging proposes 
        print("the next value is: "+str(current.next.value))
        #got an error here
        while current.next:
            if current.next.value == value:
                current.next = current.next.next
            current = current.next

我希望循环正常工作,因为有输出print(),但是我得到了这个输出:

the next value is: 3
Traceback (most recent call last):
  File "main.py", line 7, in <module>
    ll.delete(3)
  File "/home/xxx/Desktop/pc/LinkedList.py", line 6, in delete
    while (current.next):
AttributeError: 'NoneType' object has no attribute 'next'

标签: python

解决方案


确保current变量不是nullNoneType在调用其属性之前。检查您的变量是否不为空。尝试这个:

def delete(self , value):
        current = self.head
        if not current is None:
            #for debugging proposes 
            print("the next value is: "+str(current.next.value))
            #got an error here
            while current.next:
                if current.next.value == value:
                    current.next = current.next.next
                current = current.next

阅读更多关于AttributeError 这里


推荐阅读