Home > Net >  Turning a Python dict of init values into a class
Turning a Python dict of init values into a class

Time:07-20

I was wondering if there’s a way to do the following (willing to rewrite some class code if it is). I have a class:

class FSim:
    def __init__(self, filename):
        self.filename = filename
        self.df = pd.read_csv(filename)
        self.df1 = transform(self.df)
        self.value = get_value(self.df1)

So when i run:

simulation = FSim(filename)

I have an object (simulation) of type FSim.

Now, Let’s say I have a dictionary object that contains the following:

dict_values = {
    “filename”: filename,
    “df”: df,
    “df1”: df1,
    “value”: value
}

Is there a way i can turn the dict_values dictionary object into an FSim object?

CodePudding user response:

you can try something like this, The setattr() function sets the value of the attribute of an object.

class Student:
  marks = 88
  name = 'Sheeran'

person = Student()

# set value of name to Adam
setattr(person, 'name', 'Adam')
print(person.name)

# set value of marks to 78
setattr(person, 'marks', 78)
print(person.marks)

CodePudding user response:

You could create something like an alternative constructor. from_dict uses setattr to set the attributes.

class FSim:
    def __init__(self, filename=None):
        if filename:
            self.filename = filename
            self.df = pd.read_csv(filename)
            self.df1 = transform(self.df)
            self.value = get_value(self.df1)

    @classmethod
    def from_dict(cls, values):
        sim = FSim()
        for key, value in values.items():
            setattr(sim, key, value)
        return sim


dict_values = {
    "filename": filename,
    "df": df,
    "df1": df1,
    "value": value
}

simulation_1 = FSim(filename)
simulation_2 = FSim.from_dict(dict_values)
print(simulation.value)

CodePudding user response:

You can create an empty instance of FSim and skip any of its initialization by calling the constructor object.__new__ method directly. After that, assign dict_values to the __dict__ attribute of the new instance so that the instance will then have all the attributes specified in the dict:

simulation = object.__new__(FSim)
simulation.__dict__ = dict_values

CodePudding user response:

You can google 'kwargs',maybe it can help you.

  • Related