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

7
  • 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? Commented May 16, 2014 at 17:10
  • @WillBeauchamp Show us, how you want to use it and what results you expect. Commented May 16, 2014 at 17:10
  • You are right, it is ambiguous, let me try to change it. Commented May 16, 2014 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. Commented May 16, 2014 at 17:11
  • 1
    Possible duplicate of How can you set class attributes from variable arguments (kwargs) in python (already used my close vote for 'unclear what you are asking'). Commented May 16, 2014 at 17:13

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

The OP probably wants to pass in key-value pairs; x.average_height = 10, etc.
@AlexThornton Could you provide full working example? So far I see unclear question and then your answer, which does not help me either.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.