what is the idiom for copy lots of params into self?

Emin emin.shopper at gmail.com
Thu Jan 11 07:59:46 EST 2007


Dear Luis and everyone else who responded,

Thanks for your suggestions. One issue with using *args or **kw is that
I might no want to copy all the arguments to __init__ into self.

What made me ask the question in my original post was not so much that
I had to loop over the names I wanted to save, but whether it's okay to
mess with self.__dict__ or if there is another way I should be
assigning to self.

Thanks,
-Emin

On Jan 10, 9:05 pm, "Luis M. González" <luis... at gmail.com> wrote:
> Emin wrote:
> > Dear Experts,
>
> > When writing large classes, I sometimes find myself needing to copy a
> > lot of parameters from the argument of __init__ into self. Instead of
> > having twenty lines that all basically say something like self.x = x, I
> > often use __dict__ via something like:
>
> > class example:
> >      def __init__(self,a,b,c,d,e,f,g,h,i,j,k,l,m,n):
> >          for name in
> > ['a','b','c','d','e','f','g','h','i','j','k','l','m','n']:
> >              self.__dict__[name] = locals()[name]
>
> > This saves a lot of code and makes it easier to see what is going on,
> > but it seems like there should be a better idiom for this task. Any
> > suggestions?
>
> > Thanks,
> > -EminHow about using variable length argumens?
>
> class example:
>         def __init__(self, *args):
>                 for i in args:
>                         self.__dict__[i] = i
> 
> x = example('uno','dos','tres')
> 
> Luis




More information about the Python-list mailing list