4

Possible Duplicate:
How do you programmatically set an attribute in Python?

Hey, here's a dumb question: how can I set an object property given its name in a string. I have a dictionary being passed to me and I wish to transfer its values into namesake properties using code like this:

    for entry in src_dict:
          if entry.startswith('can_'):
              tgt_obj[entry] = src_dict_profile[entry]

I'm still a bit of a noob with Python so would appreciate some help. - dave.

Community
  • 1
  • 1
dave
  • 1,497
  • 2
  • 21
  • 34
  • Duplicate: http://stackoverflow.com/questions/285061/how-do-you-programmatically-set-an-attribute-in-python – S.Lott Jun 16 '10 at 14:18

3 Answers3

22
setattr(some_object, 'some_attribute', 42)
vidstige
  • 11,888
  • 8
  • 65
  • 104
Deniz Dogan
  • 24,893
  • 34
  • 106
  • 157
7

Sounds like you're looking for setattr.

Example:

for entry in src_dict:
      if entry.startswith('can_'):
          setattr(tgt_obj, entry, src_dict_profile[entry])
Hank Gay
  • 67,855
  • 33
  • 155
  • 219
1

On objects that have "dict" property

if "__dict__" in dir(obj):

you may do fun things like:

obj.__dict__.update(src_dict)
ddotsenko
  • 4,760
  • 22
  • 24