Reputation: 13
How would you go about editing a dictionary as an object attribute? Right now I have I have a class that looks like this:
class Generic_class(object):
def __init__(self):
self.attr1 = default_dict.copy()
self.attr2 = default_dict.copy()
self.attr3 = default_dict.copy()
self.attr4 = default_dict.copy()
...
I am (trying) to do it this way so that I can access the dictionaries as part of an instance of this class, and there could end up being hundreds of different instances. I would like to be able to access the attributes dynamically because the attribute to be accessed is determined by data that is retrieved by the program at run-time. These dictionaries are also going to be edited possibly hundreds of times so something like
attr_name = 'This is dynamic'
instance_dict = default_dict.copy()
instance_dict['a key'] = 'value'
setattr(x, attr_name, instance_dict)
wont work because I need previous edits to remain. Since I need to access the attributes dynamically I can't use x.y['key] = 'value'
, but I cant edit the dictionary using setattr()
so I am not sure what to do.
Upvotes: 1
Views: 1181
Reputation: 3442
Have you tried getattr
?
inst = Generic_class()
attr_name = "this is dynamic"
instance_dict = getattr(inst, attr_name, None)
if instance_dict is None:
# this attribute doesn't exist, so create it as empty dict
instance_dict = default_dict.copy()
setattr(inst, attr_name, instance_dict)
Upvotes: 0
Reputation: 362617
You'll want to "level up" in the abstraction. These hundreds of dicts should all be stored as the values in one outer dict. When the attribute names would be coming from data, don't use attributes at all - use keys.
So rather than this:
attr1 -> dict1
attr2 -> dict2
attrn -> dictn
You will have this:
myattr -> {key1: dict1,
key2: dict2,
keyn: dictn}
Upvotes: 2