[Python-ideas] Simple class initialization
Arnaud Delobelle
arnodel at gmail.com
Sat Apr 16 21:58:41 CEST 2011
On 16 Apr 2011, at 12:50, Adam Matan wrote:
> 0. Abstract
> ===========
>
> A class initialization often begins with a long list of explicit variable
> declaration statements at the __init__() method. This repetitively copies
> arguments into local data attributes.
> This article suggests some semi-automatic techniques to shorten and clarify
> this code section. Comments and responses are highly appreciated.
Following a discussion on c.l.python, I posted a recipe on ActiveState a while ago that attempted to deal with this issue:
http://code.activestate.com/recipes/551763-automatic-attribute-assignment/
From the docstring:
"""
autoassign(function) -> method
autoassign(*argnames) -> decorator
autoassign(exclude=argnames) -> decorator
allow a method to assign (some of) its arguments as attributes of
'self' automatically. E.g.
>>> class Foo(object):
... @autoassign
... def __init__(self, foo, bar): pass
...
>>> breakfast = Foo('spam', 'eggs')
>>> breakfast.foo, breakfast.bar
('spam', 'eggs')
To restrict autoassignment to 'bar' and 'baz', write:
@autoassign('bar', 'baz')
def method(self, foo, bar, baz): ...
To prevent 'foo' and 'baz' from being autoassigned, use:
@autoassign(exclude=('foo', 'baz'))
def method(self, foo, bar, baz): ...
"""
--
Arnaud
More information about the Python-ideas
mailing list