arg2
のデフォルト値を持つParent
クラスがあります。同じ属性に対して異なるデフォルト値を持つサブクラスChild
を作成したいとします。 *args
と**kwargs
をChild
に使用する必要があります。サブクラスのデフォルトのコンストラクタ引数値(親クラスから継承)
私は次のことを試してみましたが、それが動作していません。
class Parent(object):
def __init__(self, arg1='something', arg2='old default value'):
self.arg1 = arg1
self.arg2 = arg2
print('arg1:', self.arg1)
print('arg2:', self.arg2)
class Child(Parent):
def __init__(self, *args, **kwargs):
super(Child, self).__init__(*args, **kwargs)
self.arg2 = kwargs.pop('arg2', 'new value')
これが機能していません。実際に、私は得る:
>>> c = Child()
arg1: something
arg2: default value # This is still the old value
>>> c.arg2
'new value' # Seems more or less ok
>>> c = Child('one', 'two')
arg1: one
arg2: two
>>> c.arg2
'new value' # This is wrong, it has overridden the specified argument 'two'
これは起こります。 2番目の例では 'arg2'は' kwargs ['arg2'] 'ではなく' args [1] 'です。 – jonrsharpe
@jonrsharpeはい、私はそれを修正する良い方法を見つけることができないようです –