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?

2
  • yes stick your checkBox answers in a dictionary where the keys are Answer1, Answer2, etc... Commented Nov 13, 2017 at 22:00
  • did u try using .format() Something like stackoverflow.com/questions/5082452/… Commented Nov 13, 2017 at 22:01

2 Answers 2

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))
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Woked as I wanted it to work getattr(self, "checkBox_Answer"+"%d" % (A)).setText(buf[buf.find(")")+1:])
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.