I have a class whose __init__() takes a dictionary parameter. Each key in this dictionary corresponds to an instance variable. The instance variables have default values should we create this object without some or all of the dictionary keys. I have this coded as 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 # some default value
# possibly more instance variable / dictionary key assignments
So this works fine, but in reality I have 8 such dictionary key / class variable assignments and 8 default values.
How can I loop through my dictionary keys and assign them to the instance variables? I'm looking for something like:
class MyClass:
def __init__(self, param1, dict_param):
self.param1 = param1
self.key1 = 10.0 # set default value
# more defaults...
for key in dict_param.keys():
if object has class_variable key:
assign class_variable param[key]