Python Forum

Full Version: Change name of variable
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello dear users, i have function like this. In every loop of this for loop i need to change name of variable "self.labelLis" for examlpe to self.labeLis1,2,3 etc. How can i do this please?


   def clicked8(self):
       for i in range(50):
           self.labelLis = []
           self.labelLis.append(QLabel("Label"))
           self.formLayout.addRow(self.labelLis[i])
I'd suggest reviewing the comments in your previous thread on the same subject.
You can add attributes to a class using __setattr__(self, name, value).

But why would you do this? It is so much easier and cleaner to use some sort of container object. For your example I would make labelLis a list of labels.

By using __setattr__ you could now access the second label by calling self.labelLis1, and using the list you would have to call self.labelLis[1]. But that is the last time that making this a variable is easier. What if you wanted to perform the same operation on each label? Sorry, you cannot do that when you have a different variable for each label. When the labels are a list this is as simple as:
for label in labelLis:
   label['bg'] = 'blue'
Do you want to know how many labels there are? Can't do that when each label is saved using a different variable. Using a list it is easy:
count = len(labelLis)
And if you don't know how many labels there are, don't know what variables you added to you class. The only ways to find out is try to access the variable and capture the potential exception, or search through the instance variables.

You keep saying you want to make a new variable for each item but I don't think you knew what that means.