Suppose have a class with a constructor (or other function) that takes a variable number of arguments and then sets them as class attributes conditionally.
I could set them manually, but it seems that variable parameters are common enough in python that there should be a common idiom for doing this. But I'm not sure how to do this dynamically.
I have an example using eval, but that's hardly safe. I want to know the proper way to do this -- maybe with lambda?
def setAllManually(self, a=None, b=None, c=None):
self.a = a
self.b = b
self.c = c
def setAllWithEval(self, **kwargs):
for key in **kwargs:
if kwargs[param] != None
eval("self." + key + "=" + kwargs[param])
You can use the
class Foo: def setAllWithKwArgs(self, **kwargs): for key, value in kwargs.items(): setattr(self, key, value)
There is an analogous
getattr method for retrieving attributes.