1

This is what I would like.

def add_things_to_x(x,list_of_things):
    for item in list_of_things:
        x.item = item
    return x

How can I do this?

And as it seems so hard to do I am guessing there may be a better way and a reason not to do this?

An example of how I might use such a function.

average_height = 10
std_height = 3

x = load_data()

x = add_things_to_x(x,[average_height,std_height])

x.save_data()

so that later on if I pickle.load(x) I could do call x.std_height and x.average_height

Will Beauchamp
  • 579
  • 2
  • 7
  • 18
  • 1
    It's not clear what your question is; the code you showed works, but in the end you've set `x.item` to different values ending up with just the last one. Is that the intended outcome, or did you have something else in mind? – Martijn Pieters May 16 '14 at 17:10
  • @WillBeauchamp Show us, how you want to use it and what results you expect. – Jan Vlcinsky May 16 '14 at 17:10
  • You are right, it is ambiguous, let me try to change it. – Will Beauchamp May 16 '14 at 17:11
  • 1
    You want to set *dynamic attributes*, and your call won't work because the *names* you want to set are no longer associated with the *values*. – Martijn Pieters May 16 '14 at 17:11
  • 1
    Possible duplicate of [How can you set class attributes from variable arguments (kwargs) in python](http://stackoverflow.com/q/8187082) (already used my close vote for 'unclear what you are asking'). – Martijn Pieters May 16 '14 at 17:13
  • I could use setattr(x,'name',object) but I dont want to have to put in 2 bits of information {name,object}. Is there no way to intelligently and automatically get the 'name' from the object. – Will Beauchamp May 16 '14 at 17:20
  • @WillBeauchamp No there is no way to do that. – anon582847382 May 16 '14 at 17:44

1 Answers1

2

Use setattr for that sort of thing:

for k, v in {'average_height': 10, 'std_height': 3}:
    setattr(x, k, v)

At the moment at the end you've set x.item to different values ending up with just the last one. This evades that problem because the name of the attribute is sent as a string parameter.

anon582847382
  • 19,907
  • 5
  • 54
  • 57