Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Change name of variable
#1
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])
Reply
#2
I'd suggest reviewing the comments in your previous thread on the same subject.
Reply
#3
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  how can a variable change if I haven't changed it? niminim 5 2,992 Apr-07-2021, 06:57 PM
Last Post: niminim
  Change variable value during a while loop? penahuse 2 3,988 Nov-15-2020, 11:53 PM
Last Post: penahuse
  Change variable in an outside file ebolisa 5 2,568 Nov-11-2020, 04:41 AM
Last Post: ebolisa
  Python - change variable type during program execution ple 1 2,333 Apr-12-2020, 08:43 AM
Last Post: buran
  trying to change variable value with a def pythonbegginer 11 4,424 Mar-07-2020, 02:54 PM
Last Post: pythonbegginer
  change value of a global variable across all modules aster 5 4,894 Jan-01-2019, 06:42 PM
Last Post: aster
  How to change global variable in function? dan789 5 3,828 Nov-10-2018, 08:55 PM
Last Post: dan789
  Unwanted variable change in module dannyH 2 2,632 May-08-2018, 05:33 PM
Last Post: dannyH

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020