Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python- creating object instances in a loop with independent handling

I have a simple election program. The following are the requirements:

  1. class Politician
  2. Randomized votes.
  3. Taking number of politicians as input from user.

    num_politicians = input("The number of politicians: ")
    
  4. Looping and creating instances

    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
    

I have looked at:

  1. How do you create different variable names while in a loop? (Python)
  2. Python: Create instance of an object in a loop

However I could not find a solution to my problem

The Politician class is below:

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 Desired Output:

>>> 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

My problem in one statement

I want to create class instances in the for-loop in such a way that i can assign them votes randomly (This would, I suppose, require me to independently handle instances.)

Any help would be appreciated.

like image 412
AkaiShuichi Avatar asked May 24 '15 06:05

AkaiShuichi


People also ask

How do you create a loop for an object in Python?

for(var x = 1; x<=10; x++){ var Object + x = new Object(); };

How do I create a dynamic instance of a class in Python?

Classes can be dynamically created using the type() function in Python. The type() function is used to return the type of the object. The above syntax returns the type of object. print ( type ( "Geeks4Geeks !" ))

How do you make multiple objects in Python?

We can create list of object in Python by appending class instances to list. By this, every index in the list can point to instance attributes and methods of the class and can access them.

Can we create multiple objects for single class in Python?

A single class definition can be used to create multiple objects. As mentioned before, objects are independent.


1 Answers

You can store your instances in a list:

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

Now you can access individual instances:

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

I used a modified version of your class that gives each politician a default age if no is provided:

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)

Now you can work with your list of politicians:

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

prints:

The Number of politicians: 3

this:

for politician in politicians:
    print(politician)

prints:

A: 0
B: 0
C: 0

Assign random votes:

import random

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

Now:

for politician in politicians:
    print(politician)

prints:

A: 35
B: 37
C: 28

The whole program:

# 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)

And the usage:

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

UPDATE

As @martineau suggests, for real-live problems a dictionary would be more useful.

Create dictionary instead of a list:

politicians = {}

and in the loop us the name as key when you add your instance:

politicians[new_name] = Politician(new_name)
like image 67
Mike Müller Avatar answered Sep 20 '22 01:09

Mike Müller