如何将Python字典转换为Class对象

亚历克斯·普雷德斯库

我正在寻找一种简单的方法,将python dict直接转换为自定义对象,如下所示,同时又不破坏智能感知。结果不应为只读,其行为应类似于新对象。

d = {
    "key1": 1,
    "key2": 2
}

class MyObject(object):
    key1 = None
    key2 = None

# convert to object o

# after conversion
# should be able to access the defined props
# should be highlighted by intellisense
print(o.key1)
# conversion back to dict is plain simple
print(o.__dict__)
阿迪里奥

您的对象没有字段,只有类属性。您需要创建一个__init__方法,有人会称它为构造函数,但实际上它不是其他语言所理解的构造函数,因此请避免这样调用它。

class MyObject:
    def __init__(self, d=None):
        if d is not None:
            for key, value in d.items():
                setattr(self, key, value)

d = {
    "key1": 1,
    "key2": 2,
}

o = MyObject(d)

注意:以上代码将尝试将dict中的所有键值对设置为对象中的字段。某些有效的键,例如,"key.1"将不是有效的字段名称(它实际上已设置,但是您将无法使用来获得它o.key.1)。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章