メソッドのオーバーライドとsuper

入門Python3 6.4


継承時に基底クラスのメソッドをオーバーライドすることができます

class Foo():
    def hello(self):
        print("foo hello")

class Bar(Foo):
    # Foo.helloをオーバーライド
    def hello(self):
        print("bar hello")

bar = Bar()
bar.hello()
$ py main.py
bar hello


この時superを使えばBarクラスから基底クラスのメソッドへアクセスすることができます。

class Foo():
    def hello(self):
        print("foo hello")

class Bar(Foo):
    def hello(self):
        super().hello()
        print("bar hello")

bar = Bar()
bar.hello()
$ py main.py
foo hello
bar hello


ちなみにコンストラクタもオーバーライド可能です。

class Foo():
    def __init__(self,str):
        self.str = "foo " + str
    
    def hello(self):
        print(self.str)

class Bar(Foo):
    def __init__(self,str):
        super().__init__(str)
        self.str = "bar " + self.str

bar = Bar("hello")
bar.hello()
$ py main.py
bar foo hello