簡體   English   中英

Python 2.7在超類中具有關鍵字參數的功能:如何從子類訪問?

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

關鍵字參數在繼承方法中是否經過特殊處理?

當我使用定義了類的關鍵字參數調用實例方法時,一切順利。 當我從子類調用它時,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)

調用該方法時,您需要使用** kwargs,它不需要位置參數,而只需要關鍵字參數

 self.aKWMethod(**kwargs)

完成后,效果很好:

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

當您執行self.aKWMethod(kwargs)self.aKWMethod(kwargs)關鍵字參數的整個字典作為單個位置參數傳遞給(超類的) aKWMethod方法。

將其更改為self.aKWMethod(**kwargs) ,它應該可以正常工作。

僅為了以最簡單的方式說明問題所在,請注意此錯誤與繼承無關。 考慮以下情況:

>>> 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 允許使用關鍵字參數,而不能用位置參數代替。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM