This question is specifically in the context of Python classes here, but could be more generalized. I am creating a class m that will be initialized with four variables, which I would then like to assign to the instantiation of the class. Right now, this looks like this:
class mm(object):
def __init__(self, a, b, c, r):
self.a = a
self.b = b
self.c = c
self.r = r
# etc.
However, I would like to be able to assign the variables to self in one line, something like the pseudocode:
def __init__(self, a, b, c, r):
self.varname = var for var in [a, b, c, r]
It would be even better if this could be generalized to an arbitrary number of variables, so that you could get something like:
def __init__(self, **kwargs):
assign(self, varname, value) for varname, value in kwargs.iteritems()
However, as far as I know, it’s not really possible to loop through statements like that. Does anyone know a way to do this?
You can use
setattr: