There are several issues here.
queueper se refers to your class, not to an instance attribute with the same name as self.queue. You must use self.all the time. And that would really help give the class and its attribute different names in order to avoid this confusion. (This will also help to use the PEP 8 style and name the class queue.)- ,
e, return ; , , None. list[1:len(queue)] list, (self.queue). self.queue[1:len(queue)].- , , , . .
__init__ , . , . , , .list.insert list [-1] , -1.- Python 2.x, ; , `object.
- , . .
, , :
- , ,
self.queue[1:], len(self.queue). - , ,
pop(0). - ,
append. - , ,
if the_list, if len(the_list) > 0. , . - - ,
pop , , .
:
class Queue(object):
def __init__(self, queue=None):
if queue is None:
self.queue = []
else:
self.queue = list(queue)
def dequeue(self):
return self.queue.pop(0)
def enqueue(self, element):
self.queue.append(element)
, , , IndexError: dequeue from empty Queue IndexError: pop from empty list, try:
def dequeue(self):
try:
return self.queue.pop(0)
except IndexError:
raise IndexError('dequeue from empty Queue')
, , , . :
def test_queue():
q = Queue()
for i in range(10):
q.enqueue(i)
for i in range(10):
value = q.dequeue()
if value != i:
print('Value #{} should be {} but is {}'.format(i, i, value))
try:
value = q.dequeue()
except IndexError:
pass # we _want_ an error here
else:
print('#10 should raise an IndexError, but got {}'.format(value))
if __name__ == '__main__':
test_queue()
script, .
, , . , , unittest , nose, .