【发布时间】:2023-03-10 07:57:01
【问题描述】:
我在 StackOverflow 上看到过其他类似的例子,但我不明白任何答案(我还是一个新程序员),我看到的其他例子也不像我的,否则我不会不要发布这个问题。
我在 Windows 7 上运行 Python 3.2。
我以前从未遇到过这种情况,而且我已经多次以这种方式上课,所以我真的不知道这次有什么不同。唯一的区别是我没有制作所有的 Class 文件。我得到了一个模板来填写和一个测试文件来试一试。它适用于测试文件,但不适用于我的文件。我一直在以与测试文件完全相同的方式调用类中的方法(例如 Lineup.size())
这是我的班级:
类队列: # 构造函数,它创建一个新的空队列: def __init__(self): self.__items = [] # 将新项目添加到队列的后面,并且不返回任何内容: def 队列(自我,项目): self.__items.insert(0,item) 返回 # 移除并返回队列中最前面的项目。 # 如果队列为空,则不返回任何内容。 def 出队(自我): 如果 len(self.__items) == 0: 返回无 别的: 返回 self.__items.pop() # 返回队列中最前面的项目,并且不更改队列。 def 窥视(自我): 如果 len(self.__items) == 0: 返回无 别的: 返回 self.__items[(len(self.__items)-1)] # 如果队列为空,则返回 True,否则返回 False: def is_empty(self): 返回 len(self.__items) == 0 # 返回队列中的项目数: 默认尺寸(自我): 返回 len(self.__items) # 从队列中删除所有项目,并将大小设置为 0: def 清除(自我): del self.__items[0:len(self.__items)] 返回 # 返回队列的字符串表示形式: 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
当我输入“添加”作为我的决策变量时,这是我的错误消息:
第 8 行,在 builtins.AttributeError:“队列”对象没有属性“大小”
那么,这里发生了什么?这个有什么不同?
【问题讨论】:
-
看来您正在导入内置的
queue模块,而不是您自己的。尝试检查queue.__file__的设置。 -
Python 3 已经包含一个
queue模块。将您的queue.py重命名为my_queue.py,您的代码应该可以工作。 -
哦哇...我怎么没注意到?哈哈。谢谢你。那解决了它。你应该“回答这个问题”,这样我就可以给你们中的任何一个竖起大拇指并打勾。
-
如果您不想陷入自定义代码,您也可以尝试
from collections import deque,它类似于列表但非常高效,并且可以帮助您完成工作。
标签: python class python-3.x queue attributeerror