1

dictPythonのクラスのメソッド、単純なものをオーバーライドしたい: update. 少なくとも 10 個の要素を含む必要がある s で更新できることを除いて、MyDict標準と同じクラスを作成したいとしましょう。dictdict

だから私は次のように進みます:

def update(self, newdict):
    if len(newdict) <= 10: raise Exception
    self.update(newdict)

しかし、 への内部呼び出しではupdate、明らかに Python が元の関数ではなく、オーバーライドされた関数を呼び出します。関数名を変更する以外に、この状況を回避する方法はありますか?

4

2 に答える 2

4

updateサブクラスのインスタンスを として提供して、スーパークラスを呼び出す必要がありますself

def update(self, newdict):
    if len(newdict) <= 10: raise Exception
    dict.update(self, newdict)

super()実行時にスーパークラスを決定するためにも使用できます。

def update(self, newdict):
    if len(newdict) <= 10: raise Exception
    super(MyDict, self).update(newdict)

Python 3 では、次のパラメーターを省略できますsuper()

def update(self, newdict):
    if len(newdict) <= 10: raise Exception
    super().update(newdict)
于 2013-01-07T16:00:22.177 に答える
0

dictクラスから継承しますか? スーパー機能を使う

super(MyDict, self).update

トリックを行う必要があります

于 2013-01-07T16:01:28.057 に答える