【问题标题】:AttributeError: 'list' object has no attribute 'question' on PythonAttributeError:“列表”对象在 Python 上没有属性“问题”
【发布时间】:2021-07-12 17:25:37
【问题描述】:

我遇到了以下问题AttributeError,但我检查了语法和缩进,没有发现错误。谁能帮我找出问题所在?

class Question():
    def __init__(self, question, answer):
        self.question = question
        self.answer = answer

question_prompts = [
    "What color are apples?\n(a) Red/Green\n(b) Purple\n(c) Orange\n",
    "What color are bananas?\n(a) Teal\n(b) Magenta\n(c) Yellow\n",
    "What color are strawberries?\n(a) Yellow\n(b) Red\n(c) Blue\n",
]

tasks = [
    Question(question_prompts[0], "a"),
    Question(question_prompts[1], "c"),
    Question(question_prompts[2], "b"),
]

def run_test(tasks):
    score = 0
    for items in tasks:
        answer = input(tasks.question)
        if answer == tasks.answer:
            score += 1
    print("You got " + str(score) + "/" + str(len(question_prompts)) + " correct")

run_test(tasks)

例外:

AttributeError: 'list' object has no attribute 'question'

【问题讨论】:

  • tasks 是一个列表。 itemsQuestion 的一个实例。所以,answer = input(items.question).

标签: python attributes attributeerror python-class


【解决方案1】:

您正在查看整个问题列表并尝试索引 .question 属性,以便它查看列表容器而不是单个对象,这将通过以下方式修复:-

answer = input(items.question)

As items 是在循环的每次传递中包含 Question 对象的变量。您还必须相应地更改答案检查

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-21
    • 1970-01-01
    • 2020-11-18
    • 2021-07-05
    • 2021-01-18
    • 2019-08-28
    • 2021-03-28
    • 1970-01-01
    相关资源
    最近更新 更多