Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

On creating new class instance in a loop, creates the variable name class variable, any help would be great

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading