我在StackOverflow上看到过这种情况的其他例子,但是我不理解任何答案(我还是一个新的程序员),我看到的其他例子看起来也不像我的,否则我不会发布这个题 .
我在Windows 7上运行Python 3.2 .
我之前从来没有遇到这种情况,而且我已经多次这样做过课,所以这次我真的不知道有什么不同 . 唯一的区别是我没有制作所有的Class文件;我得到了一个填写的模板和一个测试文件来试试 . 它适用于测试文件,但不能处理我的文件 . 我一直在以与测试文件完全相同的方式调用类中的方法(例如Lineup.size())
这是我的 class :
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”作为我的决策变量时,这是我的错误消息:
第8行,在builtins.AttributeError:'Queue'对象没有属性'size'
那么,这里发生了什么?这个有什么不同?
2 回答
Python 3已经有一个
queue
模块(您可能需要查看) . 当您import queue
时,Python会在找到queue.py
之前找到queue.py
文件 .将
queue.py
文件重命名为my_queue.py
,将导入语句更改为from my_queue import Queue
,您的代码将按预期运行 .尝试重命名其他名称的大小或实现一个列表__items的计数器