On Jan 27, 6:32 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> Wildemar Wildenburger schrieb:
>
> > André wrote:
> >> Personally, I like the idea you suggest, with the modification that I
> >> would use "." instead of "@", as in
>
> >> class Server(object):
> >>     def __init__(self, .host, .port, .protocol, .bufsize, .timeout):
> >>         pass
>
> > I like :)
>
> > However, you can probably cook up a decorator for this (not certain, I'm
> > not a decorator Guru), which is not that much worse.
>
> > Still, I'd support that syntax (and the general idea.).
>
> Just for the fun of it, I implemented a decorator:
>
> from functools import *
> from inspect import *
>
> def autoassign(_init_):
>     [EMAIL PROTECTED](_init_)
>      def _autoassign(self, *args, **kwargs):
>          argnames, _, _, _ = getargspec(_init_)
>          for name, value in zip(argnames[1:], args):
>              setattr(self, name, value)
>          _init_(self, *args, **kwargs)
>
>      return _autoassign

Nice!  I've got a slight variation without magic argument names:

def autoassign(*names):
    def decorator(f):
        def decorated(self, *args, **kwargs):
            for name in names:
                setattr(self, name, kwargs.pop(name))
            return f(self, *args, **kwargs)
        return decorated
    return decorator

class Test(object):
     @autoassign('foo', 'bar')
     def __init__(self, baz):
         print 'baz =', baz

t = Test(foo=1, bar=2, baz=6)
# or Test(6, foo=1, bar=2)

print t.foo
print t.bar
print t.baz

--
Arnaud

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to