首页 > 解决方案 > 增加类__init__中的字典值?

问题描述

我正在尝试创建一个获取投票问题和投票选项的类,并返回元组列表中每个选项的总票数。但是,我无法获取我设置的字典__init__以保留先前实例的投票。

这是我的代码:

class Poll:
    def __init__(self, question, options):
        self.question = question
        self.options = options
        self.votes = {}

    def vote(self, option):
        if option in self.votes:
            self.votes[option] += 1
        else: 
            self.votes[option] = 1
        return True

    def get_votes(self):
        vote_list = [(key, value) for key, value in self.votes.items()]
        return vote_list


vote_1 = Poll("What is your favorite fruit?", ["Apple", "Banana"])
vote_1.vote("Apple")
vote_2 = Poll("What is your favorite fruit?", ["Apple", "Banana"])
vote_2.vote("Banana")
vote_3 = Poll("What is your favorite fruit?", ["Apple", "Banana"])
vote_3.vote("Apple")
print(vote_1.get_votes())
print(vote_2.get_votes())
print(vote_3.get_votes())

这就是我得到的:

[('Apple', 1)]
[('Banana', 1)]
[('Apple', 1)]

这就是我想要得到的:

[('Apple', 1]
[('Apple', 1), ('Banana', 1)]    
[('Apple', 2), ('Banana', 1)]

我无法将“投票”功能设置为返回投票,因为它必须返回True

我想我需要另一个函数来保存字典,但我不知道该怎么做。

标签: pythonclassdictionary

解决方案


代码几乎是正确的。该类Poll本身很好,但是您为每次投票分别实例化它,而不是每次都vote在同一个实例上调用该方法。您需要做的就是:

poll = Poll("What is your favorite fruit?", ["Apple", "Banana"])
poll.vote("Apple")
print(poll.get_votes())
poll.vote("Banana")
print(poll.get_votes())
poll.vote("Apple")
print(poll.get_votes())

尽管您也可以考虑使用循环,而不是重复代码:

poll = Poll("What is your favorite fruit?", ["Apple", "Banana"])
for option in "Apple", "Banana", "Apple":
    poll.vote(option)
    print(poll.get_votes())

顺便说一句,我向Poll全班建议的一项改进(尽管与问题没有直接关系)options是没有真正使用,除了将其分配给self.options然后不使用。您可以在vote方法中使用它来强制人们不对不是选项之一的事情进行投票。例如,如果方法开始于:

    def vote(self, option):
        if option not in self.options:
            raise ValueError("you are not allowed to vote on {}"
                             .format(option))        
        # do other stuff

然后在使用实例化后:

poll = Poll("What is your favorite fruit?", ["Apple", "Banana"])

你做了:

poll.vote("Cheese")

那么这将引发异常。


推荐阅读