Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code

Roy Smith roy at panix.com
Sat Jul 2 14:48:21 EDT 2005


In article <TmAxe.15916$mK5.1164597 at news20.bellglobal.com>,
 "Walter Brunswick" <walterbrunswick at sympatico.ca> wrote:

> Why not just update the local dictionary?
> 
> class Grouping:
>     def __init__(self,x,y,z):
>         self.__dict__.update(locals()) 

That's pretty clever.  The only minor annoyance is that it creates a 
self.self.  If that bothers you, you can fix it with:

    def __init__ (self, x, y, z):
        vars = locals()
        del vars["self"]
        self.__dict__.update(vars)

or, perhaps:

    def __init__ (self, x, y, z):
        self.__dict__.update(locals())
        del self.self

It doesn't give you all the flexibility of the original proposal (i.e. 
name-by-name selectivity of what gets imported into self), but it does 
solve the OP's OP (Original Poster's Original Problem).



More information about the Python-list mailing list