我正在尝试使用单个关键字参数扩展方法,同时保持对方法的其余部分的公正性;我只是想传递它。尝试0:
class SomeSuperclass(object):
pass # in reality: some implementation for some_method
class SomeClass(SomeSuperclass):
def some_method(self, my_kwarg=42, *args, **kwargs):
super(SomeClass, self).some_method(*args, **kwargs)
do_something_interesting_with(my_kwarg)
SomeClass().some_method('arg 0', 'arg 1', some_kwargs=5, my_kwarg=8)
这不起作用:
Traceback (most recent call last):
File "test.py", line 9, in <module>
SomeClass().some_method('arg 0', 'arg 1', some_kwargs=5, my_kwarg=8)
TypeError: some_method() got multiple values for keyword argument 'my_kwarg'
我完全理解为什么以上不起作用,但我正在寻找一种很好的方法来使它工作。这是我目前(丑陋)的解决方法:
class SomeClass(SomeSuperclass):
def some_method(self, *args, **kwargs):
my_kwarg = kwargs.get('my_kwarg', 42)
if 'my_kwarg' in kwargs:
del kwargs['my_kwarg']
super(SomeClass, self).some_method(*args, **kwargs)
do_something_interesting_with(my_kwarg)
这是每个kwarg 3条线路......
答案 0 :(得分:6)
我会使用dict.pop()
,如下所示:
class SomeSuperclass(object):
def some_method(self, *args, **kwargs):
print 'SomeSuperclass: args=%s kwargs=%s' % (args, kwargs)
class SomeClass(SomeSuperclass):
def some_method(self, *args, **kwargs):
my_kwarg = kwargs.pop('my_kwarg', 42) # 42 is the default
print 'SomeClass: my_kwarg=%s' % my_kwarg
super(SomeClass, self).some_method(*args, **kwargs)
SomeClass().some_method('arg 0', 'arg 1', some_kwargs=5, my_kwarg=8)
SomeClass().some_method('arg 0', 'arg 1', some_kwargs=5)
运行时,打印出来:
SomeClass: my_kwarg=8
SomeSuperclass: args=('arg 0', 'arg 1') kwargs={'some_kwargs': 5}
SomeClass: my_kwarg=42
SomeSuperclass: args=('arg 0', 'arg 1') kwargs={'some_kwargs': 5}
答案 1 :(得分:1)
您可以使用{}.pop()
将3行残骸变为1:
my_kwarg = kwargs.pop('my_kwarg', 42)