idiom for constructor?

Steven Bethard steven.bethard at gmail.com
Wed Jun 1 16:33:17 EDT 2005


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.)

I wouldn't actually advise this code to anyone though.  I find that if I 
have more than 3 or 4 parameters to a function, I should probably 
refactor my code.  And with 4 or fewer parameters, I don't think you 
gain any clarity by using the "self.__dict__.update" trick.

STeVe



More information about the Python-list mailing list