1

My plan is to allocate 100 Participants with random attributes to a class. What is the best way to do that without having to declare them one by one like this:

p1 = Participant() 
p2 = Participant() 
p3 = Participant() etc.

Class definition:

import names
import random

status_list = ["single", "married", "widowed", "complicated"]

class Paricipant():
    def __init__(self, name= None, age = None, status = None):
        if name is None:
            self.name = names.get_first_name()
        if age is None:
            self.age = random.randint(22, 50)
        if status is None:
            self.status = random.choice(status_list)

    def return_all(self):
        print(self.name)
        print(self.age)
        print(self.status)
martineau
  • 119,623
  • 25
  • 170
  • 301

1 Answers1

0

You can store them in a list. There are two ways to create the list:

First, you can use a list comprehension:

participants = [Paricipant() for _ in range(100)]

Alternatively, if you don't like list comprehensions, you can use a for loop instead:

participants = []
for _ in range(100):
    participants.append(Paricipant())

I also think you misspelled "Participant" (the class name is currently "Paricipant").

BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33