Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Receiving Arguments via Pointers in Python

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

like image 536
vettipayyan Avatar asked Aug 29 '26 04:08

vettipayyan


2 Answers

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
like image 161
GWW Avatar answered Aug 30 '26 20:08

GWW


Here is a simpler way to write it

def __init__(self, **options):
    vars(self).update(options)
like image 27
John La Rooy Avatar answered Aug 30 '26 19:08

John La Rooy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!