Reputation: 16835
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?
Upvotes: 5
Views: 9797
Reputation: 1123022
You cannot use farg
as 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
self.test_var_kwargs(self, 1, myarg2="two", myarg3=3)
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:
class Method(object):
def __init__(self, function, instance, cls):
self.func = function
self.instance = instance
self.cls = cls
def __call__(self, *args, **kw):
return self.func(self.instance, *args, **kw)
Your farg
keyword argument is then lumped under the **kw
catchall and passed on to the underlying function, with *args
left empty.
But the test_var_kwargs
method you defined has one positional argument (next to self
, and thus an exception is raised.
Upvotes: 7