Python 2.7函数与超类中的关键字参数:如何从子类访问?

时间:2016-10-12 14:57:48

标签: python python-2.7 inheritance variadic

关键字参数是否以某种方式特别在继承方法中处理?

当我使用其定义的类中的关键字参数调用实例方法时,一切顺利。当我从一个子类调用它时,Python抱怨传递了太多参数。

以下是这个例子。 "简单"方法不使用关键字args,继承工作正常(即使对我来说:-)" KW"方法使用关键字args,继承不再起作用......至少我看不出差异。

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')
按照我的预期,

打印thisthatthis。但

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

抛出:

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

3 个答案:

答案 0 :(得分:1)

调用方法时需要使用** kwargs,它不需要位置参数,只需关键字参数

 self.aKWMethod(**kwargs)

一旦你这样做,它就可以了:

In [2]: aClass().aSimpleMethod('this')
   ...: aSubClass().anotherSimpleMethod('that')
   ...: aClass().aKWMethod(show='this')
   ...: 
show: this
show: that
show: this

答案 1 :(得分:1)

执行self.aKWMethod(kwargs)时,您将关键字参数的整个dict作为单个位置参数传递给(超类' s)aKWMethod方法。

将其更改为self.aKWMethod(**kwargs),它应该按预期工作。

答案 2 :(得分:1)

只是为了用最简单的术语证明可能出现的问题,请注意这个错误与继承无关。考虑以下情况:

>>> def f(**kwargs):
...     pass
...
>>> f(a='test') # works fine!
>>> f('test')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: f() takes 0 positional arguments but 1 was given

关键是**kwargs 只有允许关键字参数,不能用位置参数替换。