Is it possible to loop through class attributes via string? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Is it possible to loop through class attributes via string? (/thread-8044.html) |
Is it possible to loop through class attributes via string? - 04chiak - Feb-04-2018 Hey guys, I'm stumped on this issue. I currently am referencing a UI file built in pyqt, and though it wise to create a while loop to iterate through the button commands. However, it seems to be pretty stubborn, and i'm not sure how to go about it. iconEnumerator = 0 #This works, since there is a PoseSlot_32 attribute. The button slots go from 0-32 self.PoseSlot_32.clicked.connect(self.printonetwoThree2) #This doesn't work (looping) while iconEnumerator >= 32: "self.PoseSlot_" + str(iconEnumerator) + ".clicked.connect(self.printonetwoThree2)" iconEnumerator += 1what is difficult is that i've tried #setAttr(self, "PoseSlot_32.clicked.connect()", self.printonetwoThree2) stringPoseAttribute = "self.PoseSlot_" + str(iconEnumerator) + ".clicked.connect(self.printonetwoThree2)" #eval(stringPoseAttribute) and #getAttr Doesn't seem to be useful since it keeps returning invalid object RE: Is it possible to loop through class attributes via string? - metulburr - Feb-04-2018 What is your actual purpose on doing this determines the result. From the object of the class >>> class Klass: ... def __init__(self): ... self.var = 1 ... self.pot = 'test' ... >>> obj = Klass() >>> obj.__dict__ {'var': 1, 'pot': 'test'} RE: Is it possible to loop through class attributes via string? - 04chiak - Feb-04-2018 I'm currently trying to create a button gallery, however the button's functionality is triggered but a button attribute function. The reason for iteration through all these buttons. IE self.PoseSlot_1.clicked.connect(self.printonetwoThree2) self.PoseSlot_2.clicked.connect(self.printonetwoThree2) self.PoseSlot_3.clicked.connect(self.printonetwoThree2) self.PoseSlot_4.clicked.connect(self.printonetwoThree2) ... is to create a default function on the click command if there is a null value. I just figure I could make a loop so i didn't have to copy and paste the code like above Oh yea also, All of the attributes are already generated through the UI file.* "PoseSlot_ ..." RE: Is it possible to loop through class attributes via string? - 04chiak - Feb-04-2018 Completely misunderstood the syntax of getAttr. Issue resolved getattr(self, "PoseSlot_1").setIcon(QtGui.QIcon(self.jsonFolderPath + "/icon/" + self.jsonTemplateData.values()[0][0]["icon"])) |