On Mar 31, 8:49 am, "Frank Millman" <fr...@chagford.com> wrote:
Hi all

Thanks to all for the helpful replies.

Rob, you are correct, I had not realised I was adding attributes to the class instead of the instance. Your alternative does work correctly. Thanks.

Carl, I understand your concern about modifying attributes. In my particular case, this is not a problem, as the class is under my control, and an instance will not be modified once it is set up, but I agree one must be careful not to mis-use it.

My use-case is that I want to create a number of objects, I want to store them in a tuple/list so that I can retrieve them sequentially, and I also want to retrieve them individually by name. Normally I would create a tuple and a dictionary to serve the two purposes, but I thought this might be a convenient way to get both behaviours from the same structure.

Regarding adding elements after instantiation, I would subclass 'list', as suggested by others, and then add an 'add' method, like this -

   def add(self, name, value):
       setattr(self, name, value)
       self.append(value)

I tested this and it behaves as I want.

Having said all of this, I have realised that what I probably want is an ordered dict. I will play with the one in PyPi, hopefully it will render this entire discussion redundant. It was interesting, though, and I have learned a lot.

Thanks again

Frank


--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to