class Student():
def __init__(self):
self.name = 'abc'
self.age = 24
def load():
with open('person_data.pkl', 'rb') as inp:
values = pickle.load(inp)
return values
def set_class_variables(self, values):
for a,j in values.items():
self.a = j
if __name__ == '__main__':
obj = Student()
values = {'name':'name1', "age":12, "marks":95} #this comes after loading from pickle file.
obj.set_class_variables(values)
here marks variable is not created, instead, "a’ is created with values 95. I know this is not the right way to do it, can someone tell me the right way.
>Solution :
if you set class variables instead of instance variables, you can do like this
class Student(object):
@classmethod
def set_class_variables(cls, attributes: dict):
for name, value in attributes.items():
setattr(cls, name, value) # or cls.__dict__[name] = value
if __name__ == '__main__':
values = {'name': 'name1', "age": 12, "marks": 95} # this comes after loading from pickle file.
Student.set_class_variables(values)
print(Student.name)