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?

3
  • 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". Commented Jun 26, 2019 at 6: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) Commented Jun 26, 2019 at 6:33
  • you can use the getattr and/or setattr function depending on what type of variable to set. Commented Jun 26, 2019 at 6:34

1 Answer 1

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)]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.