python运用类的投票程序代码
时间: 2024-07-10 09:00:51 浏览: 58
在Python中,我们可以创建一个简单的投票程序类来模拟选举过程。这里是一个基础的示例,使用类定义候选人、票数和投票方法:
```python
class Election:
def __init__(self, candidates):
self.candidates = candidates
self.votes = {candidate: 0 for candidate in candidates}
def vote(self, candidate):
if candidate not in self.candidates:
print(f"{candidate} is not a valid candidate.")
return
self.votes[candidate] += 1
print(f"You have voted for {candidate}. Total votes: {self.get_total_votes()}")
def get_total_votes(self):
return sum(self.votes.values())
# 示例:
candidates = ["Alice", "Bob", "Charlie"]
election = Election(candidates)
# 用户投票
election.vote("Alice")
election.vote("Bob")
election.vote("Charlie")
election.vote("Dave") # 非候选人,会给出提示
# 输出最终结果
print("Final results:")
for candidate, votes in election.votes.items():
print(f"{candidate}: {votes} votes")
阅读全文