<ul>
<li>不能在类外使用<code>self</code></李>
<li>只需使用<code>questions[q]</code>就可以返回<code>Moive</code>类的实例,在这种情况下不需要返回<code>class</code>本身</李>
<li>该属性以<code>__</code>开头,在python中被视为<code>private</code>,不能从外部访问</李>
</ul>
<h3 id="code-qmsi">code:</h3>
<pre><code>import random
class Movie:
def __init__(self, title, releaseYear, director, genre, length, rating):
self.title=title
self.releaseYear=releaseYear
self.director=director
self.genre=genre
self.length=length
self.rating=rating
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"),
"test":Movie("test_title",1978,"test_director",["test1","test2"],99,"test_rating")
}
#Determine quantity
quantity=int(input("How many questions? "))
print()
print("Here's a random selection of", quantity,"questions:")
rset = random.sample(list(questions), quantity)
print()
#Accumulator Start
total=0
qt=0
#Question Loop
for q in rset:
qt+=1
print(f"Question # {qt}:{q}")
ans=input('Answer: ')
if ans.casefold()==questions[q].title.casefold():
print('Correct! The answer is:' ,questions[q].title.casefold())
print()
total+=1
else:
print("Incorrect. The answer is:", questions[q].title.casefold())
print()
</code></pre>
<h3 id="result-dh55">result:</h3>
<pre><code>How many questions? 2
Here's a random selection of 2 questions:
Question # 1:test
Answer: a
Incorrect. The answer is: test_title
Question # 2:May the Force be with you.
Answer: Star Wars: Episode IV - A New Hope
Correct! The answer is: star wars: episode iv - a new hope
</code></pre>