'NoneType' 对象没有属性 'element'
'NoneType' object has no attribute 'element'
为什么在下面的代码中,在 while 循环中打印 head.element 时我没有收到任何错误
但是循环外的相同代码打印代码让我出错?
class node:
def __init__(self, element):
self.element = element
self.next = None
head = None
node1 = node(1)
node2 = node(2)
head = node1
node1.next = node2
while head != None:
print(head.element)
head = head.next
print(head.element)
错误是由您的最后一行代码引发的:
print(head.element)
when/if流到上面那一行,head
变量是None
,因为while
循环只有在head == None
时才结束。
while head != None:
print(head.element)
head = head.next # The last time this will return None
在上一次 while 循环迭代中,头部为 None
,您尝试打印 class None.
的 属性 元素
为什么在下面的代码中,在 while 循环中打印 head.element 时我没有收到任何错误 但是循环外的相同代码打印代码让我出错?
class node:
def __init__(self, element):
self.element = element
self.next = None
head = None
node1 = node(1)
node2 = node(2)
head = node1
node1.next = node2
while head != None:
print(head.element)
head = head.next
print(head.element)
错误是由您的最后一行代码引发的:
print(head.element)
when/if流到上面那一行,head
变量是None
,因为while
循环只有在head == None
时才结束。
while head != None:
print(head.element)
head = head.next # The last time this will return None
在上一次 while 循环迭代中,头部为 None
,您尝试打印 class None.