python - 属性访问在打印语句中有效,但在 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'
解决方案
确保current
变量不是null
或NoneType
在调用其属性之前。检查您的变量是否不为空。尝试这个:
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
这里。
推荐阅读
- python - 使用蓝图时的 Flask Sqlalchemy 循环导入
- python - 如何在 Pyomo 中索引矩阵
- java - 为什么 servlet API 不提供过滤器的排除模式?
- angular - Angular7 和 NgbModal:如何删除默认的自动对焦
- javascript - 在单词数组中找到反转的单词
- rabbitmq - Spring RabbitMQ 事务和队列溢出
- python - 具有不同大小的输出和状态的 RNNCell
- image - .pdf 总是矢量图像吗?
- powerbi - powerbi 中带有 2 个图表的一致图例颜色
- laravel - laravel 护照 oauth2 实时服务器未经身份验证 401