[EMAIL PROTECTED] je napisao/la: > Hello, > > > I have a member function with many (20) named arguments > > def __init__(self,a=1,b=2): > self.a=a > self.b=b > > I would like to get rid of the many redundant lines like self.a=a and > set the members automatically. > The list of default arguments could be given like > > def __init__(**kwargs): > arglist={"a":1,"b":2] > > if this makes things easier > > Of course there has to be a check that raises an error in case of an > unknown argument not mentioned in this list. > > > I am sure there is an elegant way how to do this, could you give me any > hints??? > > > Many thanks > > > > Daniel
def changeattrs(obj, __dict, **kwargs): for name, value in __dict.iteritems(): if hasattr(obj, name): setattr(obj, name, value) else: raise AttributeError for name in kwargs: if hasattr(obj, name): setattr(obj, name, kwargs[name]) else: raise AttributeError def locals2self(depth=0): import sys ns = sys._getframe(depth+1).f_locals obj = ns['self'] for name, value in ns.iteritems(): if name != 'self': setattr(obj, name, value) class C1(object): def __init__(self, a=1, b=2, c=3, d=4): locals2self() class C2(object): a = 1 b = 2 c = 3 d = 4 def __init__(self, **kwargs): changeattrs(self, kwargs) -- http://mail.python.org/mailman/listinfo/python-list