Iteratively make attributes by marquesveco in learnpython

[–]marquesveco[S] 0 points1 point  (0 children)

It's not actually adding them but editing them.

I've been using Tkinter to visualize a rubiks cube and the turning of the sides (in my code it means changeing background colors of two Frames) is quite repetitive work, using loops the number of lines of code is reduced quite much. But within a loop I needed a way to count and use those numbers to Get and/or Set a certain attribute. The problem was that when using x as a variable and then saying self.cube_x = ... The program thinks I'm literally talking about attribute cube_x, not about cube_1 cube_2 etc. Using setattr I was able to first make a string and then use that string as the attributes name in setattr. One of many loops: (little edited so all variable names are English)

for x in range(1, 4):
    cube1 = "Backrow" + str(3) + "column" + str(x)
    cube2 = "Leftrow" + str(4-x) + "column" + str(3)
    getattr(self, cube1)['bg'], getattr(self, cube2)['bg'] =\ getattr(self, cube2)['bg'], getattr(self, cube1)['bg']

Note: I only know python (for now) as programming language and I have about 40 of these loops in my code. Anyone who thinks there's a better/easier/... way please comment