py3k feature proposal: field auto-assignment in constructors

Russ P. Russ.Paielli at gmail.com
Mon Jan 28 04:06:14 EST 2008


On Jan 28, 12:21 am, Ben Finney <bignose+hates-s... at benfinney.id.au>
wrote:
> "Russ P." <Russ.Paie... at gmail.com> writes:
> > OK, then how about a special function that could be called from
> > inside the constructor (or anywhere else for that matter) to
> > initialize a list of data members. For example,
>
> > self.__set__(host, port, protocol, bufsize,
> >     timeout)
>
> > This would be equivalent to
>
> > self.host = host
> > self.port = port
> > # etc.
>
> > I'm not sure if that is technically feasible, but it would cut down
> > on repetition of names.
>
> It's much more attractive, because it doesn't change the function
> signature. In fact, here's a variation that doesn't even need a
> language change::
>
>     >>> class Foo(object):
>     ...     def __init__(self, spam, eggs, beans):
>     ...         self.__dict__.update(dict(
>     ...             (name, value) for (name, value) in vars().items()
>     ...             if name in ['spam', 'beans']))
>     ...
>     >>> foo = Foo("some spam", "more eggs", "other beans")
>     >>> foo.spam
>     'some spam'
>     >>> foo.eggs
>     Traceback (most recent call last):
>       File "<stdin>", line 1, in ?
>     AttributeError: 'Foo' object has no attribute 'eggs'
>     >>> foo.beans
>     'other beans'
>
> --
>  \       "If consumers even know there's a DRM, what it is, and how it |
>   `\     works, we've already failed." --Peter Lee, Disney corporation, |
> _o__)                                                             2005 |
> Ben Finney

If you can wrap that in a clean function that works for every class
you might have something.



More information about the Python-list mailing list