arguments of a function/metaclass

goodwolf Robert.Katic at gmail.com
Tue Jan 16 11:27:18 EST 2007


rubbishemail at web.de 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

A simply solution:

def __init__(self, a=1, b=2, c=3, ......):
    for key, val in locals().items():
        if key != 'self':
            setattr(self.__class__, key, val)

in addition:

def set(self, **kwarg):
    for key in kwargs:
        if hasattr(self.__class__, key):
            setattr(self.__class__, key, kwargs[key])
        else:
            raise ....

This solution is appropriate with use of proprieties.
For better proprety usage look at
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/442418




More information about the Python-list mailing list