python - 增加类__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
。
我想我需要另一个函数来保存字典,但我不知道该怎么做。
解决方案
代码几乎是正确的。该类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")
那么这将引发异常。
推荐阅读
- python-3.x - 如何在 boto 客户端创建期间指定 metadata_service_timeout?
- python - Python & matplotlib - 改变单个点的颜色
- php - home.blade.php 视图中未定义的变量 $tweet
- php - 如何在没有外来字符的情况下安全地回显数据库内容
- reactjs - useEffect 错误:缩小的 React 错误 #321(GTM 实现而不是 google analitycs)
- vb.net - VS2019 不同签名的类构造函数要求调用程序包含所有签名类型作为引用
- python - 直方图交点 - Python
- soapui - SoapUI 负载测试限制
- vb.net - 在组合框中显示颜色列表及其名称
- mysql - INSERT ...返回整行而不是指定每一列