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

Terry Hancock hancock at anansispaceworks.com
Sat Jul 2 18:17:17 EDT 2005


On Saturday 02 July 2005 05:04 am, Ralf W. Grosse-Kunstleve wrote:
> I often find myself writing::
> 
>     class grouping:
> 
>         def __init__(self, x, y, z):
>             self.x = x
>             self.y = y
>             self.z = z
>             # real code, finally

Fortunately, you don't have to, try this:
#(1)
class grouping:
    def __init__(self, *args):
        parms = ('x', 'y', 'z')
        arg_parms = zip(parms, args[:len(parms)])
        for parm, arg in arg_parms:
            setattr(self, parm, arg)

In this case, of course, this isn't any shorter, but if you have
a few dozen parameters, it can be.

Note, that it may be stylistically better to do this:
#(2)
class grouping:
    def __init__(self, **kw):
        for key, val in kw.items():
            setattr(self, key, val)

or possibly:
#(3)
class grouping:
    def __init__(self, **kw):
        parms = ('x', 'y', 'z')
        for key, val in kw.items():
            if key in parms: setattr(self, key, val)

Because, if you are going to have dozens of arguments, it will be hard
for you to remember their order in the caller, and keyword arguments
will make it possible to set them by name.  Example (2) doesn't validate
the arguments -- allowing you to set any arbitrary collection of values
you want (can be a useful way to create a shared namespace), but (3)
does (which is probably important if your class actually does specific
things with the parameters).

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com




More information about the Python-list mailing list