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.
-
2"str(showit) == Korker("test",2) #this is the line that fails" First, is it really "==" in your code? Second, please post the actual error message you're actually getting. Third, why aren't you using a dictionary for this kind of thing?S.Lott– S.Lott2011年01月05日 20:19:08 +00:00Commented Jan 5, 2011 at 20:19
-
1Are you basically trying to name variables with code? Short answer, you can't.PrettyPrincessKitty FS– PrettyPrincessKitty FS2011年01月05日 20:19:30 +00:00Commented Jan 5, 2011 at 20:19
-
1You probably want to store your objects in a list or a dictionary. It does not seem to be useful to abuse the variable namespace for this purpose.Sven Marnach– Sven Marnach2011年01月05日 20:19:45 +00:00Commented Jan 5, 2011 at 20:19
-
3@The Communist Duck: The short answer should be: "Don't do this". It is possible, but probably not desirable.Sven Marnach– Sven Marnach2011年01月05日 20:21:11 +00:00Commented Jan 5, 2011 at 20:21
-
2Why can't you use an array called h? The variables would be h[1], h[2], etc...kikito– kikito2011年01月05日 20:23:32 +00:00Commented Jan 5, 2011 at 20:23
3 Answers 3
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()).
Comments
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].
Comments
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.