0

I need to name a variable via another variable for a small game. I have made a class for all bullets and a seperate one for enemies.

class bruh(object):
    def __init__(self,x):
        print(x)
for x in range(1,11):
    x = bruh(x)

What I want the code to do is to create 10 variables each labbeled 1-10 which each are the bruh() object so they print x when created. Not sure if i'm stupid or not but is there any way to achieve this or something similar?

  • 4
    The common beginner question "how can I create variables programmatically" is almost always resolved with "don't; use a dictionary variable or a list". – tripleee Jun 26 '19 at 06:32
  • You probably just want an array/list, not really dynamic variable names (which is possible in python but really hacky and more problematic than just using a list) – kutschkem Jun 26 '19 at 06:33
  • you can use the `getattr` and/or `setattr` function depending on what type of variable to set. – ZF007 Jun 26 '19 at 06:34

1 Answers1

5

It wouldn't be so efficient to create them, instead a list would come in handy:

l = []
for x in range(1,11):
    l.append(bruh(x))

Or:

l = [bruh(x) for x in range(1, 11)]
U13-Forward
  • 69,221
  • 14
  • 89
  • 114