是否可以从 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中从字典中设置属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
python:不同包下同名的两个模块和类python: Two modules and classes with the same name under different packages(python:不同包下同名的两个模块和类)
配置 Python 以使用站点包的其他位置Configuring Python to use additional locations for site-packages(配置 Python 以使用站点包的其他位置)
如何在不重复导入顶级名称的情况下构造python包How to structure python packages without repeating top level name for import(如何在不重复导入顶级名称的情况下构造python包)
在 OpenShift 上安装 python 包Install python packages on OpenShift(在 OpenShift 上安装 python 包)
如何刷新 sys.path?How to refresh sys.path?(如何刷新 sys.path?)
分发带有已编译动态共享库的 Python 包Distribute a Python package with a compiled dynamic shared library(分发带有已编译动态共享库的 Python 包)