Queue'对象没有'size'属性
我在StackOverflow上看到过其他类似的例子,但我对那些回答都不太理解(我还是个新手程序员),而且我看到的其他例子和我的情况也不太一样,不然我就不会发这个问题了。
我在Windows 7上运行Python 3.2。
我以前从来没有遇到过这种情况,我已经用这种方式做过很多次课程,所以我真的不知道这次有什么不同。唯一的不同是我没有自己创建所有的类文件;我是根据一个模板来填的,还有一个测试文件让我试用。它在测试文件上运行得很好,但在我的文件上却不行。我调用类中的方法的方式和测试文件完全一样(例如,Lineup.size()
)。
这是我的类:
class Queue:
# Constructor, which creates a new empty queue:
def __init__(self):
self.__items = []
# Adds a new item to the back of the queue, and returns nothing:
def queue(self, item):
self.__items.insert(0,item)
return
# Removes and returns the front-most item in the queue.
# Returns nothing if the queue is empty.
def dequeue(self):
if len(self.__items) == 0:
return None
else:
return self.__items.pop()
# Returns the front-most item in the queue, and DOES NOT change the queue.
def peek(self):
if len(self.__items) == 0:
return None
else:
return self.__items[(len(self.__items)-1)]
# Returns True if the queue is empty, and False otherwise:
def is_empty(self):
return len(self.__items) == 0
# Returns the number of items in the queue:
def size(self):
return len(self.__items)
# Removes all items from the queue, and sets the size to 0:
def clear(self):
del self.__items[0:len(self.__items)]
return
# Returns a string representation of the queue:
def __str__(self):
return "".join(str(i) for i in self.__items)
这是我的程序:
from queue import Queue
Lineup = Queue()
while True:
decision = str(input("Add, Serve, or Exit: ")).lower()
if decision == "add":
if Lineup.size() == 3:
print("There cannot be more than three people in line.")
continue
else:
person = str(input("Enter the name of the person to add: "))
Lineup.queue(person)
continue
elif decision == "serve":
if Lineup.is_empty() == True:
print("The lineup is already empty.")
continue
else:
print("%s has been served."%Lineup.peek())
Lineup.dequeue()
continue
elif (decision == "exit") or (decision == "quit"):
break
else:
print("%s is not a valid command.")
continue
这是我在输入“add”作为决策变量时收到的错误信息:
line 8, in builtins.AttributeError: 'Queue' object has no attribute 'size'
那么,这里发生了什么?这次有什么不同呢?
2 个回答
-3
试着把“size”这个名字换成其他的名字,或者给列表 __items 加一个计数器,像这样:
def get_size(self):
cnt = 0
for i in self.__items:
cnt++
return cnt
14
Python 3已经有一个叫做queue
的模块(你可以去看看)。当你使用import queue
时,Python会先找到系统自带的queue.py
文件,而不是你自己写的queue.py
。
所以,你需要把自己的queue.py
文件改名为my_queue.py
,然后把导入的语句改成from my_queue import Queue
,这样你的代码就能按照你想要的方式运行了。