I have below an object:
class A:
a:str
b:str
c:str
And the dictionary is as below:
d = {"a":"abc","b":"def","d":"itf"}
After populating the dictionary in the object, params a
and b
should be "abc"
and "def"
and d
should be discarded and c
should be None.
How can I achieve this?
Edit: i want to set instance attributes not class attributes in class A.
CodePudding user response:
You can use a classmethod to load each value from the dictionary into the specific class variable.
class A:
a:str
b:str
c:str
@classmethod
def loadDict(cls, d:dict):
cls.a = d.get("a", None)
cls.b = d.get("b", None)
cls.c = d.get("c", None)
d = {"a":"abc","b":"def","d":"itf"}
A.loadDict(d)
print(A.a) # "abc"
print(A.c) # None
Trying to get A.d
results in an AttributeError.
CodePudding user response:
You can make a dict with the correct variables and update the class's __dict__
class A:
def __init__(self, **kwargs):
dictionary = {}
for k, v in kwargs.items():
if k in ["a", "b", "c"]:
dictionary[k] = v
self.a = None
self.b = None
self.c = None
dictionary["c"] = None
self.__dict__.update(**dictionary)
# define the dict with the variables and make the object
d = {"a": "abc", "b": "def", "d": "itf"}
objectWithDictVariables = A(**d)
# print the values from the object
print(objectWithDictVariables.__dict__["a"])
print(objectWithDictVariables.__dict__["b"])
print(objectWithDictVariables.__dict__["c"])