Jon
Jon

Reputation: 1

Python 3.0 - Dynamic Class Instance Naming

I want to use a while loop to initialize class objects with a simple incremented naming convention. The goal is to be able to scale the number of class objects at will and have the program generate the names automatically. (ex. h1...h100...h1000...) Each h1,h2,h3... being its own instance.

Here is my first attempt... have been unable to find a good example.

class Korker(object):

     def  __init__(self,ident,roo):
             self.ident = ident
             self.roo = roo


b = 1
hwinit = 'h'
hwstart = 0

while b <= 10:
    showit = 'h' + str(b)
    print(showit)   #showit seems to generate just fine as demonstrated by print
    str(showit) == Korker("test",2)   #this is the line that fails

    b += 1

The errors I get range from a string error to a cannot use function type error.... Any help would be greatly appreciated.

Upvotes: 0

Views: 255

Answers (3)

Lennart Regebro
Lennart Regebro

Reputation: 172407

Variables are names that point to objects that hold data. You are attempting to stick data into the variable names. That's the wrong way around.

instead of h1 to h1000, just call the variable h, and make it a list. Then you get h[0] to h[999].

Upvotes: 2

Thomas K
Thomas K

Reputation: 40390

Slightly different solution to viraptor's: use a list.

h = []
for i in range(10):
    h.append(Korker("test",2))

In fact, you can even do it on one line with a list comprehension:

h = [Korker("test", 2) for i in range(10)]

Then you can get at them with h[0], h[1] etc.

Upvotes: 1

viraptor
viraptor

Reputation: 34205

If you want to generate a number of objects, why not simply put them in an array / hash where they can be looked up later on:

objects = {}
for b in range(1,11):
    objects['h'+str(b)] = Korker("test", 2)

# then access like this:
objects['h3']

Of course there are ways to make the names available locally, but that's not a very good idea unless you know why you need it (via globals() and locals()).

Upvotes: 3

Related Questions