Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

substring variable name python

i have few variables like this:

self.lamp_1
self.lamp_2
self.lamp_3
self.lamp_4

and now i want to use each of this names is loop to call them automaticly, like this:

for i in range(1,5):
    self.canvas.itemconfig(self.lamp_/number_i_automaticly/, fill=self.color_blink)

I tried using function eval() but it doesn't work. It stops running my program.

eval("self.canvas.itemconfig(self.lamp_"+str(i)+",fill=self.color_blink)")

how can i declerate names of variables in that way, using key i?

like image 953
greg Avatar asked May 14 '26 19:05

greg


1 Answers

Use a list instead of indexed variable names:

self.lamps = [lamp_1, lamp_2, lamp_3, lamp_4]

If you insist on using indexed variable names (you shouldn't), you can use getattr():

for i in range(1, 5):
    self.canvas.itemconfig(getattr(self, "lamp_%i" % i), 
                           fill=self.color_blink)
like image 193
Sven Marnach Avatar answered May 16 '26 08:05

Sven Marnach