【问题标题】:'Queue' object has no attribute 'size'“队列”对象没有属性“大小”
【发布时间】: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


【解决方案1】:

尝试为其他名称重命名大小或对列表 __items 实现一个计数器

def get_size(self):
    cnt = 0
    for i in self.__items:
        cnt++
    return cnt

【讨论】:

    【解决方案2】:

    Python 3 已经有一个 queue 模块(您可能想看看)。当您 import queue 时,Python 在找到您的 queue.py 之前先找到 queue.py 文件。

    将您的queue.py 文件重命名为my_queue.py,将您的导入语句更改为from my_queue import Queue,您的代码将按照您的预期运行。

    【讨论】:

      猜你喜欢
      • 2021-06-27
      • 2022-06-12
      • 2021-10-29
      • 1970-01-01
      • 2021-04-09
      • 2020-11-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多