2

I am making a desktop programm with Qt+Python and currently I am facing a problem calling some attributes with variable in their names

self.checkBox_Answer1.clear()
self.checkBox_Answer2.clear()
self.checkBox_Answer3.clear()
self.checkBox_Answer4.clear()

Number is the variable, so I want something like

self."checkBox_Answer%d" % (A).clear()

where "A" is my variable which is counted, but coding this way doesnt work

Also tried

self.str("checkBox_Answer"+"%d" % (A)).clear()  
self.checkBox_Answer+"%d" % (A).clear()  

and nothing works

I know I can do something like

if A == 1:
    self.checkBox_Answer1.clear()
if A == 2:
    self.checkBox_Answer2.clear()
if A == 3:
    self.checkBox_Answer3.clear()
if A == 4:
    self.checkBox_Answer4.clear()

But isn't there more pythonic way to do this stuff?

PAXMA
  • 23
  • 6

2 Answers2

3

You can use reflection to get the name of the attribute using getattr. It will affect your performance but it's a cleanest way than a map.

It will looks like:

getattr(self, "checkBox_Answer"+"%d" % (A))
Pau Trepat
  • 697
  • 1
  • 6
  • 24
  • 1
    Thanks! Woked as I wanted it to work `getattr(self, "checkBox_Answer"+"%d" % (A)).setText(buf[buf.find(")")+1:])` – PAXMA Nov 13 '17 at 22:25
0

I would store these variables in a list:

self.checkboxAnswers = [checkBox_Answer1,etc...]

self.checkboxAnswers[A].clear()

You can access these variables in the list by using A. Note that lists start at index 0, so you'll have to increment A by one.

Mek-OY
  • 54
  • 4