简体   繁体   English

在python中使用类作为字典值

[英]Using a class as a dictionary value in python

I'm new to to Python and could use some help.我是 Python 的新手,可以使用一些帮助。 I'm trying to use several class parameters as a dictionary value and I don't know how to return the value with the class's parameter variables.我正在尝试使用多个类参数作为字典值,但我不知道如何使用类的参数变量返回该值。 Here's what I have so far:这是我到目前为止所拥有的:

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

I'd like the questions[q] to return class Movie if possible.如果可能的话,我希望问题 [q] 返回类电影。 Any suggestions?有什么建议么?

  • You can't use self outside a class.你不能在课堂外使用self
  • Just use questions[q] you can return a instance of Moive class, no need to return a class itself in the situation.只需使用questions[q]就可以返回一个Moive类的实例,在这种情况下不需要返回一个class本身。
  • The attribute start with __ treat as private in python, which can't access from outside.__开头的属性在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

Yes, that is possible.是的,这是可能的。 However, Python dicts are unordered.但是,Python dicts 是无序的。 So return the value of a dict via index does not make sense, But if you want, you can do:所以通过索引返回字典的值没有意义,但如果你愿意,你可以这样做:

value_at_index = dic.values()[index]

Instead, you will want to return the value via key, for your code:相反,您将希望通过键为您的代码返回值:

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

but right now, for your str method, you did not return anything.但是现在,对于您的str方法,您没有返回任何内容。 Keep in mind that str should return a string.请记住, str应该返回一个字符串。 For example you want to return the title, you code would be like:例如你想返回标题,你的代码是这样的:

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

Which will output:这将输出:

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

Process finished with exit code 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM