I don’t have much experience in python but I am studying **kwargs.
Afer reading a lot I understood somethings about **kwargs but I have a small problem or I am not understanding something correct.
So this works:
def test_var_kwargs(farg, **kwargs):
print "formal arg:", farg
for key in kwargs:
print "another keyword arg: %s: %s" % (key, kwargs[key])
test_var_kwargs(farg=1, myarg2="two", myarg3=3)
And prints:
formal arg: 1
another keyword arg: myarg2: two
another keyword arg: myarg3: 3
But if that function was an instance function then self would have to be included:
def test_var_kwargs(self, farg, **kwargs):
print "formal arg:", farg
for key in kwargs:
print "another keyword arg: %s: %s" % (key, kwargs[key])
self.test_var_kwargs(farg=1, myarg2="two", myarg3=3)
But this produces an error:
TypeError: test_var_kwargs() takes exactly 2 arguments (1 given)
I understand that I have to pass self like:
self.test_var_kwargs(self, farg=1, myarg2="two", myarg3=3)
Why do I have to include self as an argument in the class instance’s method?
You cannot use
fargas keyword argument in that case; it cannot be interpreted as both a positional and a keyword argument, Python interprets it as a keyword argument in this case.Use
instead.
Functions act as descriptors; when looked up on an instance, they get wrapped in a new object called a method, which automatically adds the instance as a first argument to the function when called. This wrapper essentially does this:
Your
fargkeyword argument is then lumped under the**kwcatchall and passed on to the underlying function, with*argsleft empty.But the
test_var_kwargsmethod you defined has one positional argument (next toself, and thus an exception is raised.