Python サブクラスが親メソッドを呼び出す

Pythonでは、サブクラスは super() 関数を使うことで、親クラスのメソッドを呼び出すことができます。super() 関数は、親クラスのメソッドを呼び出せるテンポラリオブジェクトを返します。サブクラスで super() 関数を使用して、親クラスのメソッドを呼び出し、必要な引数を提供できます。

下記に例を示します。

class ParentClass:
    def __init__(self):
        self.name = "Parent"

    def say_hello(self):
        print("Hello from Parent")

class ChildClass(ParentClass):
    def __init__(self):
        super().__init__()
        self.age = 10

    def say_hello(self):
        super().say_hello()  # 调用父类的say_hello方法
        print("Hello from Child")

child = ChildClass()
child.say_hello()

出力はこうなります。

Hello from Parent
Hello from Child
bannerAds