我是Python新手,需要一些帮助。我试图使用几个类参数作为字典值,但我不知道如何使用类的参数变量返回值。以下是我目前掌握的情况:
import random
class Movie:
def __init__(self, title)
self.__title=title
def __str__(self):
return
questions={
"May the Force be with you.":Movie("Star Wars: Episode IV - A New Hope",1977,"George Lucas",["Sci-fi","Action"],121,"PG")
}
print("Here's a random selection of", 2,"questions:")
rset = random.sample(list(questions), 2)
print()
#Accumulator Start
total=0
qt=0
#Question Loop
for q in rset:
qt+=1
print("Question #",qt,":",q)
ans=input('Answer: ')
if ans.casefold()==Movie(self.__title).casefold():
print('Correct! The answer is:' ,questions[q])
print()
total+=1
else:
print("Incorrect. The answer is:", questions[q])
print()
如果可能的话,我想把问题[q]带回课堂。有什么建议吗
self
李>questions[q]
就可以返回Moive
类的实例,在这种情况下不需要返回class
本身李>__
开头,在python中被视为private
,不能从外部访问李>code:
result:
是的,这是可能的。然而,Python指令是无序的。因此,通过索引返回dict的值没有意义,但如果需要,可以执行以下操作:
相反,您希望通过键返回代码的值:
但是现在,对于您的str方法,您没有返回任何内容。请记住,str应该返回一个字符串。例如,如果要返回标题,代码如下:
这将输出:
相关问题 更多 >
编程相关推荐