How do I set a property in python using its string name [duplicate]
How can I set an object property g开发者_运维问答iven 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]
setattr(some_object, 'some_attribute', 42)
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])
On objects that have "dict" property
if "__dict__" in dir(obj):
you may do fun things like:
obj.__dict__.update(src_dict)
精彩评论