Search code examples
pythonpython-2.7inheritancevariadic

Python 2.7 function with keyword arguments in superclass: how to access from subclass?


Are keyword arguments handled somehow specially in inherited methods?

When I call an instance method with keyword arguments from the class it's defined in, all goes well. When I call it from a subclass, Python complains about too many parameters passed.

Here's the example. The "simple" methods don't use keyword args, and inheritance works fine (even for me :-) The "KW" methods use keyword args, and inheritance doesn't work anymore... at least I can't see the difference.

class aClass(object):
  def aSimpleMethod(self, show):
    print('show: %s' % show)
  def aKWMethod(self, **kwargs):
    for kw in kwargs:
      print('%s: %s' % (kw, kwargs[kw]))

class aSubClass(aClass):
  def anotherSimpleMethod(self, show):
    self.aSimpleMethod(show)
  def anotherKWMethod(self, **kwargs):
    self.aKWMethod(kwargs)

aClass().aSimpleMethod('this')
aSubClass().anotherSimpleMethod('that')
aClass().aKWMethod(show='this')

prints this, that, and this, as I expected. But

aSubClass().anotherKWMethod(show='that')

throws:

TypeError: aKWMethod() takes exactly 1 argument (2 given)

Solution

  • When you do self.aKWMethod(kwargs), you're passing the whole dict of keyword arguments as a single positional argument to the (superclass's) aKWMethod method.

    Change that to self.aKWMethod(**kwargs) and it should work as expected.