I'm trying to do the following: After performing a regex group search, I'm trying to assign the results to the class properties by a specific order. the number of results from the regex search varies from 1-5 values.
class Classification():
def __init__(self, Entry):
self.Entry = Entry
self.Section = ''
self.Class = 'Null'
self.Subclass = 'Null'
self.Group = 'Null'
self.Subgroup = 'Null'
def ParseSymbol(self,regex):
Properties_Pointers = [self.Section,self.Class,self.Subclass,self.Group,self.Subgroup]
Pattern_groups = re.search(regex, self.Symbol)
i = 0
for group in Pattern_groups.groups():
Properties_Pointers[i] = group
i += 1
the problem is that for each loop iteration, instead of the class property, Properties_Pointers[i]
gets the property's value (and of course in this case I can't assign the desired value to the property).
thanks.
If you know that your regex will always contain the same number of groups, you can just use tuple unpacking:
Refer to attribute names instead, and use the
setattr()
function to store a new value onself
:setattr()
lets you set attributes based on a variable, here taking fromattributes
; there is also a companiongetattr()
function to retrieve attributes dynamically.setattr()
will set the attributes of an object based on a string name. You can rewriteParseSymbol
above:As a side note, you can iterate over both
Pattern_groups.groups()
andPattern_Pointers
simultaneously by usingzip()
. This cleans up the code by removing the index variablei
and its incrementation: