Python repeat question

Asked 2 years ago, Updated 2 years ago, 14 views

#==============================================================
self.label_5.setStyleSheet("QLabel { background-color : white; color : blue; }")
self.label_6.setStyleSheet("QLabel { background-color : white; color : blue; }")
self.label_7.setStyleSheet("QLabel { background-color : white; color : blue; }")
self.label_8.setStyleSheet("QLabel { background-color : white; color : blue; }")
#==============================================================

I tried to do the long code above using the gun as below

for i in range(5,9):
            self.label_i.setStyleSheet("QLabel { background-color : white; color : blue; }")

As you can see, the syntax error appears because you put i in the variable name.

How can we reduce the length of code at the top by using the phalanx?

python

2022-09-22 08:59

2 Answers

According to the standard, it should be like getting a list of children from the parent widget and repeating it.

The code doesn't seem to distinguish the source code that people understand from the binary code that computers understand.

Label_i can be understood by people, but there is no such thing as label_i when the source code is compiled.

Of course, Python is an interpreter language, so reflection is easy.

getattr(self, 'label_5') #label_5 field
for i in range(5, 8):
    getattr(self, 'label_{}'.format(i))

You can do it with.


2022-09-22 08:59

Next time you write a similar code, I recommend you to use the list.


2022-09-22 08:59

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.