idiom for constructor?
Steven Bethard
steven.bethard at gmail.com
Sat Jun 4 11:49:07 EDT 2005
Peter Dembinski wrote:
>class A:
> def __init__(self, a, b, c, d):
> initial = {'a' : a, 'b' : b, 'c' : c, 'd' : d}
> for param in initial.keys():
> exec "self.%s = initial['%s']" % (param, param)
This is not a good use case for exec. Use setattr:
for param in initial:
setattr(self, param, initial[param])
Or better yet, just update the instance dict:
self.__dict__.update(initial)
But this misses the OP's point. The issues was that the OP didn't want
to write a, b, c and d again. Not only does this proposal make you
write them again, it makes you write them again twice!
STeVe
More information about the Python-list
mailing list