kwargs to python instance method -
i need pass kwargs python instance method following error below.
class test(object): def __init__(self): print 'initializaed' def testmethod(self,**kwargs): each in kwargs: print each x = test() x.testmethod({"name":"mike","age":200})
error:
traceback (most recent call last): file "c:\users\an\workspace\scratch\scratch\test.py", line 20, in <module> x.testmethod({"name":"mike","age":200}) typeerror: testmethod() takes 1 argument (2 given)
x.testmethod({"name":"mike","age":200})
this invokes testmethod()
2 positional arguments - 1 implicit (the object instance, i.e. self
) , other 1 dictionary gave it.
to pass in keyword arguments, use **
operator unpacking dictionary key=value
pairs, this:
x.testmethod(**{"name":"mike","age":200})
this translates x.testmethod(name='mike', age=200)
want. can read argument unpacking in documentation.
Comments
Post a Comment