【发布时间】:2015-05-24 06:10:43
【问题描述】:
我有一个简单的选举程序。以下是要求:
-
class Politician - 随机投票。
-
将政治家的数量作为用户的输入。
num_politicians = input("The number of politicians: ") -
循环和创建实例
names = [] for x in range(num_politicians): new_name = input("Name: ") while new_name in names: new_name = input("Please enter another name: ") names.append(new_name) #### This part is the crux of my problem ### Create instances of the Politician class #### I want to do this in a way so that i can independently #### handle each instance when i randomize and assign votes
我看过:
- How do you create different variable names while in a loop? (Python)
- Python: Create instance of an object in a loop
但是我找不到解决问题的方法
政客类如下:
class Politician:
def __init__(self, name):
self.name = str(name)
self.age = age
self.votes = 0
def change(self):
self.votes = self.votes + 1
def __str__(self):
return self.name + ": " + str(self.votes)
所需的输出:
>>> The Number of politicians: 3
>>> Name: John
>>> Name: Joseph
>>> Name: Mary
>>> Processing...
(I use time.sleep(1.0) here)
>>> Mary: 8 votes
>>> John: 2 votes
>>> Joseph: 1 vote
我的问题在一个陈述中
我想在 for 循环中创建类实例,以便我可以随机分配投票(我想这需要我独立处理实例。)
任何帮助将不胜感激。
【问题讨论】:
-
我不明白这个问题,从语义上讲,实例是独立的。