Aaron Ramsey
Aaron Ramsey

Reputation: 73

FIFO dequeueing in python "AttributeError: Queue instance has no attribute 'front'?

I'm looking to make a functional (not necessarily optimally efficient, as I'm very new to programming) FIFO queue, and am having trouble with my dequeueing.

My code looks like this:

class QueueNode:
    def __init__(self, data):
        self.data = data
        self.next = None 

    def __str__(self):
        return str(self.data) 

class Queue:
    def __init__(self):
        self.front = None
        self.rear = None
        self.size = 0

    def enqueue(self, item):
        newnode = QueueNode(item)
        newnode.next = None
        if self.size == 0:
            self.front = self.rear = newnode
        else:
            self.rear = newnode
            self.rear.next = newnode.next
        self.size = self.size+1

    def dequeue(self):
        dequeued = self.front.data
        del self.front
        self.size = self.size-1
        if self.size == 0:
            self.rear = None
        print self.front #for testing

if I do this, and dequeue an item, I get the error "AttributeError: Queue instance has no attribute 'front'." I guess my function doesn't properly assign the new front of the queue? I'm not sure how to fix it though.

I don't really want to start from scratch, so if there's a tweak to my code that would work, I'd prefer that—I'm not trying to minimize runtime so much as just get a feel for classes and things of that nature.

Thanks in advance for any help.

Upvotes: 1

Views: 1120

Answers (2)

jramirez
jramirez

Reputation: 8685

You are also removing the attribute self.front then trying to access it again.

del self.front

print self.front #for testing # you are tying to use self.front but you removed it

You are missing : at the end of some of you functions.

def dequeue(self):  # <- missing that :

I'm not sure what your intent is here, but self.front is variable it has no attribute data

dequeued = self.front.data # remove the data

You are also missing a space between def and __init__

def__init__(self):

Upvotes: 1

Steve Jessop
Steve Jessop

Reputation: 279295

The problem is this line:

del self.front

This removes ("deletes") the front attribute from self. Hence the error when you try to print self.front a few lines later. There's no such thing as self.front any more.

Upvotes: 3

Related Questions