Getting arguments via pointers in Python

I have a class whose function is defined as follows. My intention is to send him a few arguments.

For testing, I called it :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 right way to handle this?

Any suggestions are welcome ......

+1
python arguments
source share
3 answers

You want to use one asterisk instead of two. Double asterisks are for named arguments. The python documentation has a good explanation if you are interested in reading further.

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

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

Would you like to call it like this:

 class_name(argument1="some value") def __init__(self, **options): for name,val in options.iteritems(): self.__dict__[name] = val 
+5
source share

Here is an easier way to write it

 def __init__(self, **options): vars(self).update(options) 
+4
source share

Form * collects positional arguments:

 def __init__(self, *options): 

and form ** collects keyword arguments:

 def __init__(self, **options): 

You provide 2 positional arguments plus an instance as self , but it should expect only 1 positional argument self .

+3
source share

All Articles