2

I have a class whose function defined like this. My intention is to send multiple arguments to it .

For testing, I called it as :class_name("argument1","argument2"), and it says: __init__accepts atmost 1 arguments , 3 given

def __init__(self, **options):
    for name in options:
        self.__dict__[name] = options[name]

What is the proper way to handle this ?

Any suggestions welcome......

River
  • 8,585
  • 14
  • 54
  • 67
vettipayyan
  • 3,150
  • 3
  • 25
  • 34

3 Answers3

5

You want to use one asterisk instead of two. Double asterisks are for named arguments. There is a nice explanation in the python documentation if you are interested in reading further.

def __init__(self, *options):
    for name in options:
        self.__dict__[name] = name

However, from your code I think the real issue is that you are calling your function incorrectly.

You would want to call it like:

class_name(argument1="some value")

def __init__(self, **options):
    for name,val in options.iteritems():
        self.__dict__[name] = val
GWW
  • 43,129
  • 11
  • 115
  • 108
4

Here is a simpler way to write it

def __init__(self, **options):
    vars(self).update(options)
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
  • @gnibbler - the Python docs warn against modifying the dict returned by `vars` - see http://docs.python.org/library/functions.html#vars – A Lee Jul 11 '11 at 21:23
  • @A Lee, when `vars` is called without an argument is is equivalent to `locals()`, and this result should not be modified. In the case of an instance, it simply returns the `__dict__` which is of course ok to modify. – John La Rooy Jul 12 '11 at 00:27
3

The * form collects positional arguments:

def __init__(self, *options):

and the ** form collects keyword arguments:

def __init__(self, **options):

You're providing 2 positional arguments plus the instance as self, but it's defined to expect only 1 positional argument self.

MRAB
  • 20,356
  • 6
  • 40
  • 33