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

时间:2015-04-28 01:08:45

标签: python attributes

我的代码出现问题。我一直收到以下错误:

AttributeError: 'NoneType' object has no attribute 'insert'

有人能告诉我为什么会收到此错误吗?这是我的代码和snippit,它导致下面的大多数问题。

class Heap(object):

    def __init__(self, items=None):

        '''Post: A heap is created with specified items.'''

        self.heap = [None]
        if items is None:
            self.heap_size = 0
        else:
            self.heap += items
            self.heap_size = len(items)
            self._build_heap()

    def size(self):

        '''Post: Returns the number of items in the heap.'''

        return self.heap_size

    def _heapify(self, position):

        '''Pre: Items from 0 to position - 1 satisfy the Heap property.
       Post: Heap Property is satisfied for the entire heap.'''

        item = self.heap[position]
        while position * 2 <= self.heap_size:
            child = position * 2
            # If the right child, determine the maximum of two children.
            if (child != self.heap_size and self.heap[child+1] > self.heap[child]):
                child += 1
            if self.heap[child] > item:
                self.heap[position] = self.heap[child]
                position = child
            else:
                break
        self.heap[position] = item

    def delete_max(self):

        '''Pre: Heap property is satisfied
       Post: Maximum element in heap is removed and returned. '''

        if self.heap_size > 0:
            max_item = self.heap[1]
            self.heap[1] = self.heap[self.heap_size]
            self.heap_size -= 1
            self.heap.pop()
            if self.heap_size > 0:
                self._heapify(1)
            return max_item

    def insert(self, item):

        '''Pre: Heap Property is Satisfied.
       Post: Item is inserted in proper location in heap.'''

        self.heap_size += 1
        # extend the length of the list.
        self.heap.append(None)
        position = self.heap_size
        parent = position // 2
        while parent > 0 and self.heap[parent] < item:
            # Move the item down.
            self.heap[position] = self.heap[parent]
            position = parent
            parent = position // 2
        # Puts the new item in the correct spot.
        self.heap[position] = item

    def _build_heap(self):

        ''' Pre: Self.heap has values in 1 to self.heap_size
           Post: Heap property is satisfied for entire heap. '''

        # 1 through self.heap_size.

        for i in range(self.heap_size // 2, 0, -1): # Stops at 1.
            self._heapify(i)

    def heapsort(self):

        '''Pre: Heap Property is satisfied.
           Post: Items are sorted in self.heap[1:self.sorted_size].'''

        sorted_size = self.heap_size

        for i in range(0, sorted_size -1):
            # Since delete_max calls pop to remove an item, we need to append a dummy value to avoid an illegal index.
            self.heap.append(None)
            item = self.delete_max()
            self.heap[sorted_size - i] = item

这是主要的堆函数,我需要从中获取函数。这是给我麻烦的代码的一部分。

    def insert(self, item):

        '''Pre: Heap Property is Satisfied.
       Post: Item is inserted in proper location in heap.'''

        self.heap_size += 1
        # extend the length of the list.
        self.heap.append(None)
        position = self.heap_size
        parent = position // 2
        while parent > 0 and self.heap[parent] < item:
            # Move the item down.
            self.heap[position] = self.heap[parent]
            position = parent
            parent = position // 2
        # Puts the new item in the correct spot.
        self.heap[position] = item

这是我的PriorityQueue类,它调用函数并帮助我将它们实现为优先级队列。

来自MyHeap导入堆的

class PriorityQueue(object):

    def __init__(self):
        self.heap = None

    def enqueue(self, item, priority):
        '''Post: Item is inserted with specified priority in the PQ.'''
        self.heap.insert(priority, item)


    def first(self):
        '''Post: Returns but does not remove the highest priority item from the PQ.'''
        return self.heap[0]


    def dequeue(self):
        '''Post: Removes and returns the highest priority item from the PQ.'''
        if Heap.size() is None:
            raise ValueError("Error your queue is empty.")
        self.first()
        self.heap.delete_max()
    def size(self):
        '''Post: Returns the number of items in the PQ.'''
        return Heap.size()

因此在此代码中,enqueue调用insert函数。

      def enqueue(self, item, priority):
        '''Post: Item is inserted with specified priority in the PQ.'''
          self.heap.insert(priority, item)

最后这是我的测试代码:

from PriorityQueue import PriorityQueue

PQ = PriorityQueue()

PQ.enqueue(1, 200)
PQ.enqueue(2, 450)
PQ.enqueue(3, 204)

这可能是一个简单的修复,但是有谁知道为什么我一直得到属性错误?

1 个答案:

答案 0 :(得分:1)

这是因为您使用self.heap初始化None

class PriorityQueue(object):
    def __init__(self):
        self.heap = None

您可能应该使用Heap()初始化:

class PriorityQueue(object):
    def __init__(self):
        self.heap = Heap()

您的代码还有其他问题:

您应该只使用一个参数致电self.heap.insert(您正在与两个人打电话):

def enqueue(self, item, priority):
    '''Post: Item is inserted with specified priority in the PQ.'''
    self.heap.insert((priority, item))

您应该使用self.heap.size(),而不是Heap.size()

if self.heap.size() == 0:
    raise ValueError("Error your queue is empty.")

以及

def size(self):
    '''Post: Returns the number of items in the PQ.'''
    return self.heap.size()

您应该从self.heap.delete_max()

返回值
def dequeue(self):
    '''Post: Removes and returns the highest priority item from the PQ.'''
    if self.heap.size() == 0:
        raise ValueError("Error your queue is empty.")
    return self.heap.delete_max()

first必须返回堆中的[1]元素,因为[0]总是None

def first(self):
    '''Post: Returns but does not remove the highest priority item from the PQ.'''
    return self.heap.heap[1]