Reputation: 31
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)?
Upvotes: 3
Views: 1260
Reputation: 10391
You need need implement either str
or repr
for your class Queue
before printing
Upvotes: 1
Reputation: 132
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
Upvotes: 0