9

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]
0

3 Answers 3

29
setattr(some_object, 'some_attribute', 42)
Sign up to request clarification or add additional context in comments.

2 Comments

Please, no semicolons. :-D
This doesn't use the @property.setter function though does it... how would you set the property through that?
8

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])

Comments

1

On objects that have "dict" property

if "__dict__" in dir(obj):

you may do fun things like:

obj.__dict__.update(src_dict)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.