【Python入門】Pythonのsuper関数とは?使い方と活用方法を徹底解説(Python 3.11)

Python

はじめに

Pythonのオブジェクト指向プログラミング(OOP)では、クラスの継承を活用することでコードの再利用性を高めることができます。その際に便利なのが super() 関数です。

super() を使うことで、親クラスのメソッドを呼び出したり、適切なクラスのメソッド解決順序(MRO: Method Resolution Order)を保つことができます。本記事では super() 関数の基本から応用例までを詳しく解説していきます。

super関数とは?

super() 関数は、子クラス内で親クラスのメソッドを呼び出すための組み込み関数です。特に、多重継承を使用する場合に、MRO に基づいて適切な親クラスのメソッドを取得できるメリットがあります。

super関数を使うメリット

  • 親クラスのメソッドを明示的に呼び出すことができる
  • コードの可読性と保守性が向上する
  • 多重継承時のMRO(メソッド解決順序)を適切に管理できる

super関数の基本構文

super() 関数の基本的な使い方は以下のとおりです。

class Parent:
    def greet(self):
        print("Hello from Parent!")

class Child(Parent):
    def greet(self):
        super().greet()  # 親クラスの greet メソッドを呼び出す
        print("Hello from Child!")

child = Child()
child.greet()

出力結果

Hello from Parent!
Hello from Child!

このように、 super().メソッド名() を使うことで、親クラスのメソッドを呼び出せます。

super関数の使用例

コンストラクタの呼び出し

子クラスの __init__ メソッド内で super() を使用し、親クラスの __init__ を呼び出すことができます。

class Parent:
    def __init__(self, name):
        self.name = name
        print(f"Parent initialized with name: {self.name}")

class Child(Parent):
    def __init__(self, name, age):
        super().__init__(name)  # 親クラスのコンストラクタを呼び出す
        self.age = age
        print(f"Child initialized with age: {self.age}")

child = Child("Alice", 12)

出力結果

Parent initialized with name: Alice
Child initialized with age: 12

super関数の応用例

多重継承とメソッド解決順序(MRO)

Python では多重継承を使用することができますが、 super() を用いることでMROを考慮しながら適切に親クラスのメソッドを呼び出すことができます。

class A:
    def show(self):
        print("A's show method")

class B(A):
    def show(self):
        print("B's show method")
        super().show()

class C(A):
    def show(self):
        print("C's show method")
        super().show()

class D(B, C):
    def show(self):
        print("D's show method")
        super().show()

obj = D()
obj.show()

出力結果

D's show method
B's show method
C's show method
A's show method

このように、 super() を適切に使用することで、MRO に基づいた順序でメソッドが実行されます。

まとめ

  • super() 関数は親クラスのメソッドを呼び出すために使用する
  • コードの再利用性と可読性を向上させる
  • 多重継承時に MRO に基づいて適切なメソッドを呼び出すことができる

Python の super() は便利な関数なので、適切に活用してクラス設計を行いましょう。