0
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.

nolanding
  • 103
  • 8

1 Answers1

0

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)

mxp-xc
  • 456
  • 2
  • 6
  • Is there some way to do it using object of the class? – nolanding Dec 21 '21 at 12:24
  • Both classes and instances can be called. `Student.set_class_varialbe(xxx)` or `Student().set_class_variable(xxx)` – mxp-xc Dec 21 '21 at 12:29
  • But this is the class property, not the instance property Because I think your naming may need instance attributes. if you need instance property, you should use `def set_class_variables(self, attributes: dict):` – mxp-xc Dec 21 '21 at 12:31
  • I needed it only for some instances, different instances can have different variables coming into the picture. Using your logic was able to resolve it. Thanks. – nolanding Dec 21 '21 at 12:39