简体   繁体   中英

How to add members to a class dynamically using options as coonstructor args in python?

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 ie providing the options during object instantiation?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM