-1

I have a class and I want to create dynamically instances of that class. I don't know the exact number of instances so that I dont want to create that classes by a known variable like this:

class Person:
    def __init__(self, age, gender):
        self.age=age
        self.gender=gender

P1=Person(23, "M")
P2=Person(64, "F")
P3=Person(12, "M")

I am looking for sth like

i=0
maxPopulation=10
while i< maxPopulation:
    Person(randomx, randomy)
    i+=1

But that way I don't know how to access the instances. During the runtime.

I am not looking for a random function.

Pluxyy
  • 95
  • 2
  • 11

1 Answers1

2

Add them to a list.

i=0
maxPopulation=10
people = []
while i< maxPopulation:
    people.append(Person(randomx, randomy))
    i+=1

Or, cleaned up a bit to be more Pythonic:

maxPopulation=10
people = []
for _ in range(maxPopulation):
    people.append(Person(randomx, randomy))

Or even more Pythonic:

max_population = 10
people = [Person(randomx, randomy) for _ in range(max_population)]
John Gordon
  • 29,573
  • 7
  • 33
  • 58