__autoinit__ (Was: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code)
Scott David Daniels
Scott.Daniels at Acm.Org
Sat Jul 9 20:21:26 EDT 2005
Ralf W. Grosse-Kunstleve wrote:
> My initial proposal
> (http://cci.lbl.gov/~rwgk/python/adopt_init_args_2005_07_02.html) didn't
> exactly get a warm welcome...
>
> And Now for Something Completely Different:
>
> class autoinit(object):
>
> def __init__(self, *args, **keyword_args):
> self.__dict__.update(
> zip(self.__autoinit__.im_func.func_code.co_varnames[1:], args))
> self.__dict__.update(keyword_args)
> self.__autoinit__(*args, **keyword_args)
Should be:
class autoinit(object):
def __init__(self, *args, **keyword_args):
for name, value in zip(self.__autoinit__.im_func.func_code.
co_varnames[1:], args):
setattr(self, name, value)
for name, value in keyword_args.items():
setattr(self, name, value)
self.__autoinit__(*args, **keyword_args)
Since using setattr will take care of any slots used in other classes.
Not all data is stored in the __dict__.
For example:
class Example(autoinit):
__slots__ = 'abc',
def __autoinit__(self, a=1, abc=1):
print a, abc
a = Example(1,2)
print a.__dict__
print a.a
print a.abc
--Scott David Daniels
Scott.Daniels at Acm.Org
More information about the Python-list
mailing list