I am trying to simulate a collection of objects in python (2). A collection must create a specific attribute (integer, float, or any immutable object) of objects accessible through the list interface.
(1)
>>> print (collection.attrs) [1, 5, 3] >>> collection.attrs = [4, 2, 3] >>> print (object0.attr == 4) True
I especially expect this list interface in the collection to reassign one attribute of an object, e.g.
(2)
>>> collection.attrs[2] = 8 >>> print (object2.attr == 8) True
I am sure that this is a fairly common situation, unfortunately, I could not find a satisfactory answer on how to implement it in stackoverflow / google, etc.
Behind the scenes, I expect object.attr be implemented as a mutable object. Somehow, I also expect the collection to contain a "list of links" for object.attr , and not the links themselves (immutable).
I ask for your suggestion on how to solve this in an elegant and flexible way.
A possible implementation that allows (1), but not for (2),
class Component(object): """One of many components.""" def __init__(self, attr): self.attr = attr class System(object): """One System object contains and manages many Component instances. System is the main interface to adjusting the components. """ def __init__(self, attr_list): self._components = [] for attr in attr_list: new = Component(attr) self._components.append(new) @property def attrs(self):
The !!! line breaks (2), because we create a new list whose entries refer to the values โโof all Component.attr , and not to the links to the attributes themselves.
Thanks for your input.
Thexma