idiom for constructor?
Peter Dembinski
pdemb at gazeta.pl
Sat Jun 4 05:52:37 EDT 2005
Steven Bethard <steven.bethard at gmail.com> writes:
> Mac wrote:
>> Is there a nice Python idiom for constructors which would expedite
>> the following?
>> class Foo:
>> def __init__(self, a,b,c,d,...):
>> self.a = a
>> self.b = b
>> self.c = c
>> self.d = d
>> ...
>
> py> class Foo(object):
> ... def __init__(self, a, b, c, d):
> ... params = locals()
> ... del params['self']
> ... self.__dict__.update(params)
> ...
> py> vars(Foo(1, 2, 3, 4))
> {'a': 1, 'c': 3, 'b': 2, 'd': 4}
>
> Just make sure that "params = locals()" is the first line in
> __init__ method. (Otherwise you might have other local variables
> slip in there.)
Or write it like this, using Python's dynamic code execution:
#v+
class A:
def __init__(self, a, b, c, d):
initial = {'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4}
for param in initial.keys():
exec "self.%s = initial['%s']" % (param, param)
#v-
--
http://www.peter.dembinski.prv.pl
More information about the Python-list
mailing list