Python-在具有独立处理的循环中创建对象实例

Aka*_*chi 4 python class instances

我有一个简单的选举计划.以下是要求:

  1. class Politician
  2. 随机投票.
  3. 以政治家的数量作为用户的投入.

    num_politicians = input("The number of politicians: ")
    
    Run Code Online (Sandbox Code Playgroud)
  4. 循环和创建实例

    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
    
    Run Code Online (Sandbox Code Playgroud)

我看过:

  1. 如何在循环中创建不同的变量名?(蟒蛇)
  2. Python:在循环中创建对象的实例

但是我无法找到解决问题的方法

政治家课程如下:

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)
Run Code Online (Sandbox Code Playgroud)

期望的输出:

>>> 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
Run Code Online (Sandbox Code Playgroud)

我的问题在一个声明中

我想在for循环中创建类实例,以便我可以随机分配它们(我想,这会要求我独立处理实例.)

任何帮助,将不胜感激.

Mik*_*ler 9

您可以将实例存储在列表中:

politicians = []
for name in 'ABC':
    politicians.append(Politician(name))
Run Code Online (Sandbox Code Playgroud)

现在您可以访问各个实例:

>>> politicians[0].name
'A'
Run Code Online (Sandbox Code Playgroud)

我使用了类的修改版本,如果没有提供,则为每个政治家提供默认年龄:

class Politician:

    def __init__(self, name, age=45):
        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)
Run Code Online (Sandbox Code Playgroud)

现在,您可以使用您的政治家名单:

print('The Number of politicians: {}'.format(len(politicians)))
Run Code Online (Sandbox Code Playgroud)

打印:

The Number of politicians: 3
Run Code Online (Sandbox Code Playgroud)

这个:

for politician in politicians:
    print(politician)
Run Code Online (Sandbox Code Playgroud)

打印:

A: 0
B: 0
C: 0
Run Code Online (Sandbox Code Playgroud)

分配随机投票:

import random

for x in range(100):
    pol = random.choice(politicians)
    pol.votes += 1
Run Code Online (Sandbox Code Playgroud)

现在:

for politician in politicians:
    print(politician)
Run Code Online (Sandbox Code Playgroud)

打印:

A: 35
B: 37
C: 28
Run Code Online (Sandbox Code Playgroud)

整个计划:

# Assuming Python 3.

class Politician:

    def __init__(self, name, age=45):
        self.name = str(name)
        self.age = age
        self.votes = 0

    def change(self):
        self.votes = self.votes + 1

    def __str__(self):
        return '{}: {} votes'.format(self.name, self.votes)

num_politicians = int(input("The number of politicians: "))
politicians = []
for n in range(num_politicians):
    if n == 0:
        new_name = input("Please enter a name: ")
    else:
        new_name = input("Please enter another name: ")
    politicians.append(Politician(new_name))

print('The Number of politicians: {}'.format(len(politicians)))
for politician in politicians:
    print(politician)

print('Processing ...')
for x in range(100):
    pol = random.choice(politicians)
    pol.votes += 1

for politician in politicians:
    print(politician)
Run Code Online (Sandbox Code Playgroud)

用法:

The number of politicians: 3
Please enter a name: John
Please enter another name: Joseph
Please enter another name: Mary
The Number of politicians: 3
John: 0 votes
Joseph: 0 votes
Mary: 0 votes
Processing ...
John: 25 votes
Joseph: 39 votes
Mary: 36 votes
Run Code Online (Sandbox Code Playgroud)

UPDATE

正如@martineau建议的那样,对于实际问题,字典会更有用.

创建字典而不是列表:

politicians = {}
Run Code Online (Sandbox Code Playgroud)

在循环中,当您添加实例时,我们将名称作为键:

politicians[new_name] = Politician(new_name)
Run Code Online (Sandbox Code Playgroud)

  • 我建议将“ Politician”实例存储在以其名称为关键字的字典中,因为在现实生活中,投票方式是如何产生的(而不是从它们的列表中随机选择一个)。 (2认同)