I'd like to add an attribute to an instance which is in a set.
The set of objects of the class Problem is identified by attribue uid (that's why they are hashed and compared):
class Problem:
allowed_keys = [
'flag1',
'a_list_of_objects'
]
def __init__(self, uid, name, **kwargs):
self.uid = uid
self.name = name
self.__dict__.update((k, v) for k, v in kwargs.iteritems() if k in self.allowed_keys)
def __eq__(self, other):
return isinstance(other, self.__class__) and getattr(other, 'uid', None) == self.uid
def __hash__(self):
return hash(self.uid)
def __ne__(self, other):
return not self.__eq__(other)
def __repr__(self):
return json.dumps(self.__dict__, sort_keys=True)
All instances of this problem are added to a set.
problem_set = set()
problem1 = Problem(uid="abc123", name="name1", flag1=True)
problem_set.add(problem1)
problem2 = Problem(uid="xyz789", name="name2", flag2=False)
problem_set.add(problem2)
Now if I want to update the object problem1 with another attribute (it will never exist before), it just won't add the a_list_of_objects to the existing problem1
my_list = [{"a": "avalue", "b": "bvalue"}]
problem3 = Problem(uid="abc123", name="name1", a_list_of_objects=my_list
print list(problem_set)
# same list as before
What do I need to do in order to achieve this? Using @property and create getters and setters for each attribute of class Problem?