親クラスのメソッドをオーバーライドして新しい機能を追加する

2024年6月25日

親クラスのメソッドをオーバーライドして新しい機能を追加するだけなら、super()を使用して親クラスのメソッドを呼び出すことができます。以下はその方法を示した例です。

python
class ParentClass:
    def some_method(self):
        print("ParentClass method")

class ChildClass(ParentClass):
    def some_method(self):
        super().some_method()  # 親クラスのメソッドを呼び出す
        print("Additional functionality in ChildClass method")

# ChildClassのインスタンスを作成
child = ChildClass()
child.some_method()

この例では、ChildClasssome_methodは親クラスのsome_methodを呼び出し、その後に新しい機能を追加しています。

未分類

Posted by ぼっち