class Queue(object):
def __init__(self):
self.items=[]
def enqueue(self,item):
self.items.insert(0,item)
def isempty(self):
return self.items==[]
def dequeue(self):
if not self.isempty():
return self.items.pop()
else:
raise Exception('Queue is empty')
def size(self):
return len(self.items)
def peek(self):
if not self.isempty():
return self.items[-1]
else:
raise Exception('Queue is empty')
def main():
queue =Queue()
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
print(queue.size())
print(queue.peek())
print(queue.dequeue())
print(queue.peek())
if __name__=='__main__':
main()
# queue.peek()#当我使用任何方法时,它显示了这个
Traceback (most recent call last): File "<pyshell#6>", line 1, in
<module>
queue.peek() AttributeError: 'Queue' object has no attribute 'peek'
答案 0 :(得分:3)
正确格式化和缩进后,它可以正常工作:
class Queue:
def __init__(self):
self.items=[]
def enqueue(self, item):
self.items.insert(0, item)
def isempty(self):
return self.items==[]
def dequeue(self):
if not self.isempty():
return self.items.pop()
else:
raise Exception('Queue is empty')
def size(self):
return len(self.items)
def peek(self):
if not self.isempty():
return self.items[-1]
else:
raise Exception('Queue is empty')
def main():
queue =Queue()
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
print(queue.size())
print(queue.peek())
print(queue.dequeue())
print(queue.peek())
main()
答案 1 :(得分:0)
似乎是def main():并且前面的行没有正确缩进。