您可以做一些類似的引用的答案,除了刪除特定於您的子類的項目。
class Thing:
def __init__(self, arg1, arg2, arg3, arg4, kw1=None, kw2=None):
print('Thing args:',arg1,arg2,arg3,arg4)
print('Thing kw:',kw1,kw2)
class SubThing(Thing):
def __init__(self, *args, **kw):
"""SubThing(arg1, arg2, arg3, arg4, arg5, arg6, kw1=None, kw2=None,
kw3=None, kw4=None)
"""
if len(args) != 6:
raise TypeError(
"SubThing() takes 6 positional arguments but {} were given"
.format(len(args)))
arg5, arg6 = args[4:]
kw3 = kw.pop('kw3', None)
kw4 = kw.pop('kw4', None)
super().__init__(*args[:4], **kw)
SubThing(1,2,3,4,5,6,kw1='kw1',kw4='kw4')
print('---- but populating kwargs from positional args stops working ----')
Thing(1,2,3,4, 'kw1', 'kw2')
SubThing(1,2,3,4,5,6,'kw1','kw2')
這導致在第二個例子中
Thing args: 1 2 3 4
Thing kw: kw1 None
---- but populating kwargs from positional args stops working ----
Thing args: 1 2 3 4
Thing kw: kw1 kw2
Traceback (most recent call last):
File "n.py", line 24, in <module>
SubThing(1,2,3,4,5,6,'kw1','kw2')
File "n.py", line 14, in __init__
.format(len(args)))
TypeError: SubThing() takes 6 positional arguments but 8 were given
注意,你失去了一些功能,因爲特別的位置參數並沒有在關鍵字參數自動填充。你可以用更多的編碼來解決這個問題,或者只是接受限制。許多使用*args, **kw
的課程忘記了這麼做,以至於你的公司很好。
簡答:不,沒有辦法做到這一點,而不寫出你想傳遞的所有參數。 – poke
有* args和** kwargs,但我不認爲這正是你所要求的。 –