在python中从字典中设置属性

问题描述

是否可以从 python 中的字典中创建一个对象,使得每个键都是该对象的一个​​属性?

Is it possible to create an object from a dictionary in python in such a way that each key is an attribute of that object?

类似这样的:

 d = { 'name': 'Oscar', 'lastName': 'Reyes', 'age':32 }

 e = Employee(d) 
 print e.name # Oscar 
 print e.age + 10 # 42 

我认为这几乎与这个问题相反:Python 字典对象的字段

I think it would be pretty much the inverse of this question: Python dictionary from an object's fields


解决方案

当然,是这样的:

class Employee(object):
    def __init__(self, initial_data):
        for key in initial_data:
            setattr(self, key, initial_data[key])

更新

正如 Brent Nash 建议的那样,您也可以通过允许关键字参数来使其更加灵活:

As Brent Nash suggests, you can make this more flexible by allowing keyword arguments as well:

class Employee(object):
    def __init__(self, *initial_data, **kwargs):
        for dictionary in initial_data:
            for key in dictionary:
                setattr(self, key, dictionary[key])
        for key in kwargs:
            setattr(self, key, kwargs[key])

那么你可以这样称呼它:

Then you can call it like this:

e = Employee({"name": "abc", "age": 32})

或者像这样:

e = Employee(name="abc", age=32)

甚至像这样:

employee_template = {"role": "minion"}
e = Employee(employee_template, name="abc", age=32)

相关文章