"André" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
If one goes back to the original idea instead, the decision of using
automatic assignment should depend on the signature of the __init__
function.  Here's an implementation (using "_" instead of "." as it
would lead to a syntax error):

from functools import *
from inspect import *

def autoassign(_init_):
     @wraps(_init_)
     def _autoassign(self, *args, **kwargs):
         argnames, _, _, _ = getargspec(_init_)
         for name, value in zip(argnames[1:], args):
             if name.startswith("_"):
                 setattr(self, name[1:], value)
         _init_(self, *args, **kwargs)

     return _autoassign

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

t = Test(1, 2, 3)
print t.foo
print t.bar
print t.baz

#== the output is

baz = 3
1
2
Traceback (most recent call last):
File "/Users/andre/CrunchySVN/branches/andre/src/tools_2k.py", line
24, in exec_code
    exec code in local_dict
  File "User's code", line 23, in <module>
AttributeError: 'Test' object has no attribute 'baz'
=================================

I think this version, with this name convention, is nice enough to possibly 
go in the stdlib if there were an appropriate place for it.  Not sure where 
though.  If there were a classtools module....

tjr



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

Reply via email to