3

I am trying to code my first Queue class. So far I have this code that seemes to work:

class Queue(list):
    def __init__(self):
        self = []

    def insert(self, x):
        self.append(x)
        return self

    def delete(self):
        if len(self) == 0:
            print "The queue is empty"
        else:
            self.remove(self[0])
            return self

However, I was recomended to rewrite it, and when I try something like this I got wrong results:

class Queue:
    def __init__(self):
        self.items = []

    def insert(self, x):
        self.items.append(x)

Test:

queue = Queue()
print queue
queue.insert(5)
print queue

Got:

<__main__.Queue instance at 0x0000000002A2F148>
<__main__.Queue instance at 0x0000000002A2F148>

Could you, please, explain me the difference between two approaches and why the second doesn't work (although I saw it on many websites)?

3
  • 1
    Second one works, just override` __str__` or do print queue.items Commented Jan 21, 2016 at 12:27
  • how would you run your first method and what is the expected output of your second method Commented Jan 21, 2016 at 12:28
  • The expected ouputs for the tests (see "Test" above) are [], [5] respectively. I got it using the first code version and following the str advise (Thank you!) with the second code version. Commented Jan 21, 2016 at 19:53

2 Answers 2

1

You need need implement either str or repr for your class Queue before printing

Sign up to request clarification or add additional context in comments.

Comments

0

Inside the rewrite, you might want to return the value of insert, and in the calling, assign it to a variable:

queue = Queue()
print queue #should show something like <__main__.Queue instance at 0x(some numbers here)>
newQueue = queue.insert(5)
print newQueue

and inside the function, changing it to something like:

def insert(self, x):
    self.items.append(x)
    return self.items

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.