py3k feature proposal: field auto-assignment in constructors

Ben Finney bignose+hates-spam at benfinney.id.au
Mon Jan 28 03:21:48 EST 2008


"Russ P." <Russ.Paielli 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



More information about the Python-list mailing list