0

I want to create my Python class which will dynamically build its members in the constructor based on the options. Check the following sample code that I am trying to build.

options = {
'param1' = 'v1'
'param2' = 2
'param3' = bool
'param4' = {}
}

class MyCustomObject:
  def __init__(self, options):
    self.props = {}
    for key in options.keys():
      self.props[key] = options[key]

a1 = MyCustomObject(options)

# I want to access the attributes of the props using dot
a1.param1 = 10
print(a1.param1)

If I had known what options I need to add to the my object when defining the class, the I could have added following to the class definition:

@property
def param1(self):
  return self.options['param1']

@param1.setter(self, value)
  self.options['param1'] = value

How to achieve the same behavior dynamically i.e. providing the options during object instantiation?

Ronak SHAH
  • 81
  • 9
  • 2
    Does this answer your question? https://stackoverflow.com/questions/1639174/creating-class-instance-properties-from-a-dictionary/1639215#1639215 – N.Moudgil Feb 20 '20 at 05:23

1 Answers1

1

You can make use of setattr method of Python.

setattr(object, name, value)

The setattr() function sets the value of the attribute of an object.

options = {'param1' :'v1','param2' : 2,'param3' : "bool",'param4' : {}}
class MyCustomObject:
    def __init__(self, options):
        for key in options.keys():
            setattr(self, key, options[key])
a1 = MyCustomObject(options)
  • Thanks, But I think I need to rephrase the question. I am trying to add properties to the class dynamically based on the options. Please check my question again. – Ronak SHAH Jul 16 '20 at 15:47