我正在尝试使用收藏库中的双端队列,但出现错误:
'collections.deque'对象没有属性'appendLeft'。
我不太确定这里发生了什么...我正在导入库并按照文档使用。我必须错过一些确实很明显的东西,但不能动弹。
import unittest
import collections
class animal_shelter():
def __init__(self):
self.cats = collections.deque()
self.dogs = collections.deque()
def enqueue(self, animal):
if animal.type == 'dog':
self.dogs.appendLeft(animal)
elif animal.type == 'cat':
self.cats.appendLeft(animal)
def dequeue_cat(self):
if len(self.cats) > 0:
return self.cats.pop().name
else:
return None
def dequeue_dog(self):
if len(self.dogs) > 0:
return self.dogs.pop().name
else:
return None
def is_empty(self):
return len(self.dogs) == 0 and len(self.cats) == 0
def dequeue_any(self):
if self.is_empty():
return None
if len(self.dogs) >= len(self.cats):
return self.dogs.pop().name
else:
return self.cats.pop().name
class Test(unittest.TestCase):
def test_simple(self):
shelter = animal_shelter()
shelter.enqueue(Animal('dog', 'rex'))
shelter.enqueue(Animal('dog', 'max'))
shelter.enqueue(Animal('cat', 'felix'))
self.assertEqual(shelter.dequeue_any(), 'rex')
self.assertEqual(shelter.dequeue_cat(), 'felix')
self.assertEqual(shelter.dequeue_cat(), None)
self.assertEqual(shelter.dequeue_dog(), 'max')
self.assertEqual(shelter.dequeue_any(), None)
class Animal():
def __init__(self, type, name):
self.type = type
self.name = name
if __name__ == "__main__":
unittest.main()
Traceback (most recent call last):
File "animal_shelter.py", line 42, in test_simple
shelter.enqueue(Animal('dog', 'rex'))
File "animal_shelter.py", line 11, in enqueue
self.dogs.appendLeft(animal)
AttributeError: 'collections.deque' object has no attribute 'appendLeft