我有以下类,它返回给定kwargs作为输入的字典.
class Emp_Constant:
def __init__(self, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)
但是,在某些情况下,我想将字典作为此类的输入传递,并将键值作为变量进行访问.
例如,如果我的字典是{‘name’:’Tome’,’age’:’26’},那么
我想访问’Tom’,如下所示:
set = {'name': 'Tom', 'age':'26'}
a = Emp_Constant(set)
first_emp = a.NAME (where NAME is a variable that holds value of key 'name')
这有可能实现吗?
最佳答案 当然,使用“double-splat”运算符将字典解压缩为关键字参数,然后使用getattr:
In [30]: class Emp_Constant:
...: def __init__(self, **kwargs):
...: for key, value in kwargs.items():
...: setattr(self, key, value)
...:
In [31]: data = {'name': 'Tom', 'age':'26'}
...: a = Emp_Constant(**data)
...:
...: NAME = 'name'
...:
...:
In [32]: getattr(a, NAME)
Out[32]: 'Tom'