So I'm currently converting my non-object oriented python code to an object oriented design. This is an example of what my file looks like.
[object1] # this only has keys 1, 2 and 3
key1: "value 1"
key2: "value 2"
key3: "value 3"
[object2] # this only has keys 1, 2 and 4
key1: "different value 1"
key2: "different value 2"
key4: "value 4"
[object3] # this has all possible keys 1, 2, 3, 4, 5
key1: "another different value 1"
key2: "another different value 2"
key3: "different value 3"
key4: "different value 4"
key5: "value 5"
I parse this to create key:value pairs in a dictionary for each (non-created at this point) object. So my list of all possible keys, and lists of dictionary keys would look like this, for these three objects: (pseudo-code)
possibleKeyList = ['key1', 'key2', 'key3', 'key4', 'key5']
dictionary1 keyList = ['key1', 'key2', 'key3'] # has keys 1, 2, 3
dictionary2 keyList = ['key1', 'key2', 'key4'] # has keys 1, 2, 4
dictionary3 keyList = ['key1', 'key2', 'key3', 'key4', 'key5'] # has all possible keys
As you can see, each dictionary may have all possible keys, or only a few, etc (but the values are still different). When I create a new class Object, I pass in the specific dictionary. I want to initialize the keys found in that dictionary to their respective values...and if the key ISN'T in the dictionary (like how dictionary2 does not have 'key3' or 'key5'), then that attribute isn't created. This is what I am figuring out how to do here:
Class MyClass( object ):
def __init__(self, **kwargs):
possibleKeys = ['key1', 'key2', 'key3', 'key4', 'key5']
for key in kwargs.keys():
if key in possibleKeys:
# create attribute for this instance using the key:value pair
else:
# don't create the attribute, but also don't have a default blank value
dictionary = {'key1': 'different value 1', 'key2': 'different value 2', 'key4': 'value 4'}
newObject = MyClass(**dictionary)
I tried avoiding an AttributeError by setting ALL possible attributes to default values ( "", [], or False), then only replacing these defaults if the key is present in the dictionary. This gives me what I want...but for some objects, I only have one or two attributes, and the rest are just empty/default and I don't want a bunch of place holders that don't need to be there taking up space in this object
Is this the best way to go about this? I have also looked at things like setattr but I am not sure how everything ties in (init, setting attributes if they are present in **kwargs etc.
Thanks everyone. I hope I was clear enough.
EDIT I used this and it seems to work, but I will have to test it and make sure it is doing what I need.
class MyClass( object ):
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
# method to produce dictionary for specified term/object
newObject = MyClass(**dictionary)
print newObject.<key>