There is a bit of unnecessary repetition in the class definition below.
class Example(object): def __init__(self, lots, of, init, args): self.lots = lots self.of = of self.init = init self.args = args # Do stuff
The autoassign
decorator defined in autoassign.py (download here) makes __init__
assign its
arguments automatically as attributes of self
class Example(object): @autoassign def __init__(self, lots, of, init, args): # Do stuff
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): ...
The decorator is designed to behave well with default argument values. Here is an example of using these:
>>> class Test(object): ... @autoassign('foo', 'bar') ... def __init__(self, foo, bar=3, baz=6): ... "some clever stuff going on here" ... print 'baz =', baz ... >>> class Test2(object): ... @autoassign ... def __init__(self, foo, bar): pass ... >>> class Test3(object): ... @autoassign(exclude=('foo', 'bar')) ... def __init__(self, foo, bar, baz=5, **kwargs): pass ... >>> t = Test(1, 2, 5)baz = 5>>> u = Test(foo=8)baz = 6>>> v = Test2(10, 11) >>> w = Test3(100, 101, foobar=102) >>> >>> print Test.__init__.__doc__some clever stuff going on here>>> >>> print t.foo1>>> print t.bar2>>> >>> print u.foo8>>> print u.bar3>>> >>> print v.foo, v.bar # 10 1110 11>>> print w.baz, w.foobar # 5 1025 102>>> for obj, attr in ('w', 'foo'), ('w', 'bar'), ('t', 'baz'): ... try: ... getattr(globals()[obj], attr) ... except AttributeError: ... print '%s.%s raises AttributeError' % (obj, attr) ...w.foo raises AttributeError w.bar raises AttributeError t.baz raises AttributeError>>>