简体   繁体   中英

How do I return dictionary value as variable within the class

I have the following class that returns the dictionary given the kwargs as an input.

class Emp_Constant:
    def __init__(self, **kwargs):
        for key, value in kwargs.items():
            setattr(self, key, value)

However, in some instances, I would like to pass the dictionary as an input to this class and access the key values as variables.

For example, if my dictionary is {'name': 'Tome', 'age':'26'} , then I would like to access 'Tom' as below:

set = {'name': 'Tom', 'age':'26'}
a = Emp_Constant(set)
first_emp = a.NAME (where NAME is a variable that holds value of key 'name')

Is this possible to achieve?

只需使用dict拆包

a = Emp_Constant(**set)

Sure, use the "double-splat" operator to unpack the dictionary as key-word arguments, and then use 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'

Using obj_dict = Emp_Constant(**set)


Alternative way, using the EasyDict library:

from easydict import EasyDict as edict

set = {'name': 'Tom', 'age':'26'}
obj_dict = edict(set)

print(obj_dict.name)

[Out]:

'Tom'

You mean you want the class to take in name and age either way?

How about:

class Emp_Constant:
def __init__(self, useADict=None, **kwargs):
    if useADict:
        self.name = useADict.name
        self.age = useADict.age
    else:
        for key, value in kwargs.items():
            setattr(self, key, value)

The problem is that your passing the dictionary as the first parameter, instead of using **- in your example, you should have done:

set = {'name': 'x', 'age': 10}
a = Emp_Constant(**set)

Then you can access a.name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM