在python中将类用作字典值

2024-06-16 11:53:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我是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]带回课堂。有什么建议吗


Tags: theself参数titledefrandommovieqt
2条回答
  • 不能在类外使用self
  • 只需使用questions[q]就可以返回Moive类的实例,在这种情况下不需要返回class本身
  • 该属性以__开头,在python中被视为private,不能从外部访问

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()

result:

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

是的,这是可能的。然而,Python指令是无序的。因此,通过索引返回dict的值没有意义,但如果需要,可以执行以下操作:

value_at_index = dic.values()[index]

相反,您希望通过键返回代码的值:

value = questions["May the Force be with you."]

但是现在,对于您的str方法,您没有返回任何内容。请记住,str应该返回一个字符串。例如,如果要返回标题,代码如下:

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 self.__title


questions = {
    "May the Force be with you.": Movie("Star Wars: Episode IV - A New Hope", 1977, "George Lucas",
                                        ["Sci-fi", "Action"], 121, "PG")
}

# Determine quantity
print(questions)
for keys in questions:
    print(questions[keys])

这将输出:

{'May the Force be with you.': <__main__.Movie object at 0x00000268062039C8>}
Star Wars: Episode IV - A New Hope

Process finished with exit code 0

相关问题 更多 >