我正在上一門初學者課程,當我到達這里時,講師為課程制作了一個單獨的檔案,然后將其匯入。我剛剛在頂部添加了這個類,因為我以前見過它作業。雖然它不像這樣作業,但從另一個檔案匯入它是有效的。我究竟做錯了什么?
運行程式時的完整錯誤訊息:
File "C:/Users/user/PycharmProjects/pythonProject1/app.py", line 54, in RunTest
ans = input(Class.question)
AttributeError: type object 'Class' has no attribute 'question'
class Class:
def __init__(self, question, answer):
self.question = question
self.answer = answer
QuestionPrompts = [
"\n\n1. \na)\nb)\nc)\nd)\nYour Answer: ",
"\n\n2. \na)\nb)\nc)\nd)\nYour Answer: ",
"\n\n3. \na)\nb)\nc)\nd)\nYour Answer: ",
"\n\n4. \na)\nb)\nc)\nd)\nYour Answer: ",
"\n\n5. \na)\nb)\nc)\nd)\nYour Answer: ",
"\n\n6. \na)\nb)\nc)\nd)\nYour Answer: ",
"\n\n7. \na)\nb)\nc)\nd)\nYour Answer: ",
"\n\n8. \na)\nb)\nc)\nd)\nYour Answer: ",
"\n\n9. \na)\nb)\nc)\nd)\nYour Answer: ",
"\n\n10. \na)\nb)\nc)\nd)\nYour Answer: "
]
questionArray = [
Class(QuestionPrompts[0], "a"),
Class(QuestionPrompts[1], "c"),
Class(QuestionPrompts[2], "b"),
Class(QuestionPrompts[3], "d"),
Class(QuestionPrompts[4], "c"),
Class(QuestionPrompts[5], "a"),
Class(QuestionPrompts[6], "b"),
Class(QuestionPrompts[7], "c"),
Class(QuestionPrompts[8], "d"),
Class(QuestionPrompts[9], "b")
]
def RunTest(questions):
score = 0
for question in questions:
ans = input(Class.question)
if ans == Class.answer:
score = 1
else:
print("Aww man, you got this question wrong therefore lost :(\n"
"You got " str(RunTest(questionArray)) "/10 right tho!")
return score
print("Your Score: " str(RunTest(questionArray)) "!") #added this part to check if I absolutely need to call the RunTest from outside
uj5u.com熱心網友回復:
您正在將Class物件串列傳遞給 RunTest 函式。
當您遍歷此串列時,請參考當前物件的.question和.answer屬性。
def RunTest(questions):
score = 0
for question in questions:
ans = input(question.question)
if ans == question.answer:
uj5u.com熱心網友回復:
這是因為您需要首先創建該類的實體,
例子:
>>> class MyClass:
... def __init__(self,question,answer) -> None:
... self.question = question
... self.answer = answer
您需要首先將類實體化為一個物件:
>>> myobject = MyClass(question="how good is potato",answer="delicious")
那么你可以呼叫self.question:
>>> myobject.question
"how good is potato"
>>> myobject.answer
"delicious"
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/411844.html
標籤:
下一篇:如何從類中的物件呼叫函式?
