Set attributes from dictionary in python(在python中从字典中设置属性)
本文介绍了在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)
这篇关于在python中从字典中设置属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
编程基础网
本文标题为:在python中从字典中设置属性
基础教程推荐
猜你喜欢
- 尝试制作WhatsApp机器人 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
