首页 > 解决方案 > 在 Python 教程中获取属性错误:answer = input(question.prompt) AttributeError: 'str' object has no attribute 'prompt'

问题描述

我是一个新手,在这里看到的在线 youtube 课程中只学习了大约 10 小时:

https://www.youtube.com/watch?v=rfscVS0vtbw&t=622s在 3 小时 58 分钟。我可能会超越自己,需要回溯并重新学习基础知识。

多项选择计划

导入一个名为 Question 的类文件。提示用户 3 个问题,跟踪这些问题和答案,并在最后打印分数。

错误:

answer = input(question.prompt) ---
AttributeError: 'str' object has no attribute 'prompt'
class Question:
    def __init__(self, prompt, answer):
        self.prompt = prompt
        self.answer = answer


from Question import Question

question_prompts = [
    "what color are apples?\n(a) Red\n(b) Purple\n(c) Orange\n\n",
    "what color are bananas?\n(a) Teal\n(b) Magenta\n(c) Yellow\n\n",
    "what color are strawberries?\n(a) Yellow\n(b) Red\n(c) Blue\n\n"
]
questions = [
    Question(question_prompts[0], "a"),
    Question(question_prompts[1], "c"),
    Question(question_prompts[2], "b"),
"""array of question objects we want to ask on our test"""
]

def run_test(questions):
    score = 0
    for question in questions:
        answer = input(question.prompt)
        if answer == question.answer:
            score += 1
    print("You got  " + str(score) + "/" + str(len(questions)) + "Correct")

run_test(questions)

标签: pythonstringattributes

解决方案


列表的最后一个元素是三引号字符串。但是,没有 Question 类的实例。但由于它是列表的一个元素,python 尝试获取实例变量提示。

它找不到元素,因为没有类的实例。

删除线


推荐阅读