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......

2
  • 6
    N.B: * does not represent a pointer in Python. Commented Jul 11, 2011 at 3:17
  • That is a good question! Commented Jul 11, 2011 at 20:33

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

4

Here is a simpler way to write it

def __init__(self, **options):
    vars(self).update(options)

2 Comments

@gnibbler - the Python docs warn against modifying the dict returned by vars - see docs.python.org/library/functions.html#vars
@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.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.