用不同的** kwargs字典实例化类对象 - python

时间:2015-10-14 16:52:54

标签: python oop dictionary init kwargs

所以我目前正在将我的非面向对象的python代码转换为面向对象的设计。这是我的文件的样子的一个例子。

[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"

我解析这个在字典中为每个(此时未创建)对象创建键:值对。因此,对于这三个对象,我的所有可能键列表和字典键列表都是这样的:(伪代码)

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

正如您所看到的,每个字典可能包含所有可能的键,或者只有少数键等(但值仍然不同)。当我创建一个新的类Object时,我传入特定的字典。我想将字典中找到的密钥初始化为各自的值......如果密钥中的密钥ISN&#T;(例如字典2没有' key3'或' key5& #39;),然后创建该属性。这就是我要弄清楚如何做到这一点:

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)

我尝试通过将所有可能的属性设置为默认值("",[]或False)来避免AttributeError,然后仅在字典中存在键时才替换这些默认值。这给了我想要的东西......但对于某些物品,我只有一两个属性,其余的只是空/默认,我不想要一堆不需要的占位符在这个对象中占用空间

这是最好的方法吗?我也看过像setattr这样的东西,但我不确定所有内容是如何关联的( init ,设置属性,如果它们存在于** kwargs等中。

谢谢大家。我希望我很清楚。

修改 我使用它并且它似乎工作,但我将测试它并确保它正在做我需要的。

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>

0 个答案:

没有答案