python - Class instantiation with a dictionary parameter and class variables with default values -


i have class __init__() takes dictionary parameter. each key in dictionary corresponds instance variable. instance variables have default values should create object without or of dictionary keys. have coded such:

class myclass:     def __init__(self, param1, dict_param):         self.param1 = param1         if 'key1' in dict_param:             self.key1 = dict_param['key1']         else:             self.key1 = 10.0  # default value         # possibly more instance variable / dictionary key assignments 

so works fine, in reality have 8 such dictionary key / class variable assignments , 8 default values.

how can loop through dictionary keys , assign them instance variables? i'm looking like:

class myclass:     def __init__(self, param1, dict_param):         self.param1 = param1         self.key1 = 10.0  # set default value         # more defaults...          key in dict_param.keys():             if object has class_variable key:                assign class_variable param[key] 

like this:

def __init__(self, param1, dict_param):     self.param1 = param1     self.key1 = 10.0  # set default value     # more defaults...      key, value in dict_param.iteritems():         if hasattr(self, key):            setattr(self, key, value) 

you create dictionary of default values , use that:

def __init__(self, param1, dict_param):     self.param1 = param1     default_vals = {         'key1': 'default 1',         'key2': 'default 2',         'etc': 'and on'     }      key, value in default_vals.iteritems():         setattr(self, key, dict_param.get(key, value)) 

this approach lets use dict.get grab value dict_param if exists, or use value default_vals if no value provided in dict_param. also, depending on defaults come from, define default_vals @ class level (that is, outside __init__ inside class) or globally in module.

note not have class variables here. have instance variables.


Comments

Popular posts from this blog

shopping cart - Page redirect not working PHP -

php - How to modify a menu to show sub-menus -

python - Installing PyDev in eclipse is failed -