Reputation: 7
Let's say that I have to create a class that has a LOT of variables. Could I use a for loop to set each to it's self? that is:
class New(object):
def __init__(self, var1, var2, var3, var4, var5, var6):
for x in [var1, var2, var3, var4, var5, var6]:
self.x = x
Obviously the above code doesn't work, but is it possible to do this? A better way to do this? rather than typing
self.var1 = var1
self.var2 = var2
etc.?
Upvotes: 0
Views: 38
Reputation: 65791
You can either store a list of attribute names ...
In [1]: class New(object):
...: names = ['foo', 'bar']
...: def __init__(self, *args):
...: for k, v in zip(New.names, args):
...: setattr(self, k, v)
...:
In [2]: a = New(1, 2)
In [3]: a.foo
Out[3]: 1
or use keyword arguments:
In [1]: class New(object):
...: def __init__(self, **kwargs):
...: for k, v in kwargs.iteritems():
...: setattr(self, k, v)
...:
In [2]: a = New(foo=1, bar=2)
In [3]: a.foo
Out[3]: 1
Upvotes: 1