在python中设置字典中的属性 [英] Set attributes from dictionary in python

查看:331
本文介绍了在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 

我认为这与该问题几乎完全相反:来自对象的字段

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)

这篇关于在python中设置字典中的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆