开发者

How do I set a property in python using its string name [duplicate]

开发者 https://www.devze.com 2023-01-03 12:02 出处:网络
This question already has answers here: How do you programmatically set an attribute? (5 answers) Closed 2 months ago.
This question already has answers here: How do you programmatically set an attribute? (5 answers) Closed 2 months ago.

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

精彩评论

暂无评论...
验证码 换一张
取 消