I would like to write a function to append an attribute of a Python object, the attribute is a list.
Here is my code, which sets the attribute to a given value. Is there a simpler/cleaner way to this..
class Obj(object):
def __init__(self):
self.a = 2
self.b = []
self.c = []
def append_att(self, att):
at = getattr(self, att)
at.append(self.a)
setattr(self,att, at)
obj = Obj()
obj.append_att('b')
obj.append_att('b')
print obj.b
getattr(self, att).append(self.a)setattr(self,att, at)?Explicit is better than implicit!You would normally dogetattr(obj, 'b').append(obj.a)without defining any methods.self.bholds reference to thelistinstance and you don't have to reassign it. Modification to the list is transparently seen byself.b.