16

It baffles me how I can't find a clear explanation of this anywhere. Why and when do you need to call the method of the base class inside the same-name method of the child class?

class Child(Base):
    def __init__(self):
        Base.__init__(self)

    def somefunc(self):
        Base.somefunc(self)

I'm guessing you do this when you don't want to completely overwrite the method in the base class. is that really all there is to it?

4

2 に答える 2

13

通常、これは、基本クラスのメソッドを完全に置き換えるのではなく、変更して機能を拡張したい場合に行います。defaultdictこれの良い例です:

class DefaultDict(dict):
    def __init__(self, default):
        self.default = default
        dict.__init__(self)

    def __getitem__(self, key):
        try:
            return dict.__getitem__(self, key)
        except KeyError:
            result = self[key] = self.default()
            return result

これを行う適切な方法は、基本クラスを直接呼び出す代わりにを使用するsuperことです。そのようです:

class BlahBlah(someObject, someOtherObject):
    def __init__(self, *args, **kwargs):
        #do custom stuff
        super(BlahBlah, self).__init__(*args, **kwargs) # now call the parent class(es)
于 2012-05-02T06:37:36.463 に答える
2

クラスとメソッドに完全に依存します。

基本メソッドが実行される前後に何かをしたい場合、または異なる引数で呼び出す場合は、明らかにサブクラスのメソッドで基本メソッドを呼び出します。

メソッド全体を置き換えたい場合は、明らかに呼び出しません。

于 2012-05-02T06:30:04.127 に答える