-2

I have 10 check-boxes and to check whether the checkbox is checked or not, I was trying to use loop. tacb1 is the name of the 1st checkbox, tacb2 is the name of 2nd checkbox and so on. I want to use a loop which looks something like:

    for i in range(1,11):                        
        if self.tacb'"+i+"'isChecked() == True:
            print("hi")  
        else:
            print("bye")

It is throwing the error for the line self.tacb'"+i+"'isChecked() as invalid syntax. How to concatenate a variable with self?

  • 1
    You cannot concatenate object references and strings. Use `getattr(self, 'tacb{}'.format(i)).isChecked()`. See [How to access object attribute given string corresponding to name of that attribute](https://stackoverflow.com/questions/2612610/how-to-access-object-attribute-given-string-corresponding-to-name-of-that-attrib) – musicamante Oct 16 '20 at 11:03

2 Answers2

1

I think the best way to do this is to store all checkboxs instance into a list like that :

self.all_checkboxs = [checkox_a, checkox_b, ..., checkox_n]

And then you can iterate through like this:

for checkbox in self.all_checkboxs:
    if checkbox.isChecked():
        bar()
    else:
        foo()

If you really need to use strings, you can use python exec(), but I not recommend this way.

AlexLaur
  • 335
  • 4
  • 13
1

AlexLaur's answer using lists is the best way to do this but in the interest of completeness, here is an example of how you would use getattr to do the same thing

class MyClass:
    def __init__(self):
        self.item1 = 1
        self.item2 = 2
        self.item3 = 3

    def check(self):
        for i in range(1,4):
            print(getattr(self,f'item{i}'))

c = MyClass()
c.check()
scotty3785
  • 6,763
  • 1
  • 25
  • 35