1 回答

TA貢獻1811條經驗 獲得超6個贊
我認為您錯誤地使用了Question您制作的課程。你試圖做Question = data.prompt[1]這并沒有真正意義。Question 是一個類,因此您將使用它來創建對象的實例。此外,您的班級期望值prompt并answer傳遞給它。按照您現在的設置方式,您可以按照new_question = Question("What color is the sky?", "blue"). 但是,我認為在此代碼中創建類沒有多大用處,因為您沒有附加任何方法......
下面是一個測驗類思想的例子,可以幫助你掌握 OOP 編程的概念:
import random
questions = [
"What color is the sky?",
"What year is it?"
]
answers = [
"blue",
"2019"
]
class Question:
def __init__(self):
index = random.randint(0, len(questions) - 1)
self.answer = answers[index]
self.question = questions[index]
def check_valid(self, guess):
if guess == self.answer:
return True
else:
return False
if __name__ == "__main__":
name = str(input("What's your name?\n"))
print('Welcome then {} welcome to the quiz!'.format(name))
while True:
new_question = Question()
check = False
while check is not True:
print(new_question.question)
user_guess = str(input('What do you think the answer is?\n'))
check = new_question.check_valid(user_guess)
您可以看到,在該__init__(self):部分中,代碼并未真正進行任何主要計算,而只是設置了以后可以調用的內容,例如new_question.question. 但是,您可以連接方法,像類check_valid(由壓痕連接到類def),再后來就用在這些方法的實例創建類的。我的代碼中沒有很多函數(例如退出循環的能力),但希望這能幫助您更深入地理解 OOP!
添加回答
舉報