0

I was wondering if there is a way that you can make a class instance by using concatenation. (setting a class name like person1, person2, etc... , automatically)

I tried to make a code like:

class ID:
    def __init__(self):
        self.price = 2000

for i in range(50):
     string = person + str(i)
     string = ID()

But for some reason it didn't work.

Why can't this be defined this way?

Is this even possible?

martineau
  • 119,623
  • 25
  • 170
  • 301
  • mind if i post an alternative answer? xD – Novus Edge Dec 20 '20 at 07:13
  • AcupofRamen: How are you going to write code that uses the names of these variables if you know know how many of them there beforehand. – martineau Dec 20 '20 at 07:16
  • For the sake of completeness: `exec(f"person{i} = ID()")` would also do the job... BUT: There is a good reason, this is not a common pattern. Just from the small code example, I wouldn't value your coding skills too high (wrong indentation, `person` instead of `"person"`, no fealing what happens at `string = ID()`, ...). Therefore, I doubt your really need the pattern. Usually, if you want to handle multiple instances of a class, use a `list`, a `set`, a `dict`, a `tuple`, ... The best choice depends on your use case. Please have a look on these data structures first :) – matheburg Dec 20 '20 at 07:34
  • novus: Go ahead! I would love more comments – AcupofRamen Dec 21 '20 at 00:09
  • Martineau: Well, the for loop goes on for a decided amount of time, so I thought they can be used freely... – AcupofRamen Dec 21 '20 at 00:11

1 Answers1

0

usually people use a dictionary for this

people = {}

for i in range(50):
   people["person"+str(i)] = ID()

if you are really determined to make a global variable you certainly can... but its a much better idea to use a dictionary

if you really wanted a variable named person1..50 though you could just do as follows

for i in range(50):
    globals()['person'+str(i)] = ID()

print(person2)

but your ide and anyone who has to work with your code in the future will not appreciate it

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179