'NoneType' 对象没有属性 'value'

'NoneType' object has no attribute 'value'

使用"delete_entire(self)"方法删除整个链表时。它抛出 无属性错误 。虽然上面的代码 运行 没问题。它没有打印空白列表,而是给出了无属性错误。

class Node:
    def __init__(self,value):
        self.value = value
        self.next = None
    
class CircularSinglyLinkedList:
    def __init__(self):
        self.head = None
        self.tail = None
        
    

    def __iter__(self):
        node = self.head
        
        while True:
            yield node
            if node.next is self.head:
                break
            node = node.next
        
    

    def insertion(self, value, location):
    
        new_node = Node(value)
    
        if self.head is None:
            self.head = new_node
            self.tail = new_node
            self.tail.next = self.head
    
        else:
        
            if location == 0:
            
                new_node.next = self.head
                self.head = new_node
                self.tail.next = new_node
            
            elif location == -1:
                self.tail.next = new_node
                new_node.next = self.head
                self.tail = new_node
            
            else:
            
                temp_node = self.head
                index = 0
                while index < location -1:
                
                    if temp_node.next is self.head:
                        break
                    
                    temp_node = temp_node.next
                    index += 1
            
                next_node = temp_node.next
                temp_node.next = new_node
                new_node.next = next_node
            
                if new_node.next is self.head:
                    self.tail = new_node
               
#---------------------------------------------------------------------------------------------#

    # deleting the entire linked list

    def delete_entire(self):
        self.head = None
        self.tail.next = None
        self.tail = None 




cll = CircularSinglyLinkedList()
cll.insertion(2,1)
cll.insertion(3,2)
cll.insertion(5,3)
cll.insertion(6,4)
cll.insertion(0,0)
cll.insertion(10,-1)
print([node.value for node in call])

输出 = [0, 2, 3, 5, 6, 10]

cll.delete_entire()
print([node.value for node in call])

AttributeError: 'NoneType' 对象没有属性 'value'

预期输出为

[ ]

您的 __iter__() 方法总是产生一次,即使列表为空,因为它会在检查 node 是否为 None 之前 yield node。当列表为空时,将产生 None,调用者将尝试使用 None.value.

一旦 nodeNone,您应该停止循环。

def __iter__(self):
    node = self.head
    
    while node:
        yield node
        node = node.next