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

Python- creating object instances in a loop with independent handling

我有一个简单的选举程序。要求如下:

  • class Politician
  • 随机投票。
  • 把政治家的数量作为用户的输入。

    1
    num_politicians = input("The number of politicians:")
  • 循环和创建实例

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    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
  • 我看过:

  • 在循环中如何创建不同的变量名?(Python)
  • python:在循环中创建对象的实例
  • 但是我找不到解决我问题的办法

    政治家阶层如下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    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)

    所需输出:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    >>> 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循环中创建类实例,这样我就可以随机地为它们分配投票(我想,这需要我独立地处理实例)。

    任何帮助都将不胜感激。


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

    1
    2
    3
    politicians = []
    for name in 'ABC':
        politicians.append(Politician(name))

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

    1
    2
    >>> politicians[0].name
    'A'

    我使用了你们班的一个修改版本,如果没有提供,给每个政客一个默认年龄:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    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)

    现在你可以和你的政治家名单一起工作了:

    1
    print('The Number of politicians: {}'.format(len(politicians)))

    印刷品:

    1
    The Number of politicians: 3

    这是:

    1
    2
    for politician in politicians:
        print(politician)

    印刷品:

    1
    2
    3
    A: 0
    B: 0
    C: 0

    分配随机投票:

    1
    2
    3
    4
    5
    import random

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

    现在:

    1
    2
    for politician in politicians:
        print(politician)

    印刷品:

    1
    2
    3
    A: 35
    B: 37
    C: 28

    整个计划:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    # 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)

    用法:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    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

    更新

    正如@martineau所建议的,对于现实生活中的问题,字典可能会更多。有用的。

    创建字典而不是列表:

    1
    politicians = {}

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

    1
    politicians[new_name] = Politician(new_name)