Python super() – Python 3 super()

Pythonのsuper()関数は、明示的に親クラスを参照することができます。これは、親クラスの関数を呼び出したい場合に便利です。

Pythonのsuper

Pythonのsuper()関数を理解するには、Pythonの継承について知っておく必要があります。Pythonの継承では、サブクラスがスーパークラスから継承されます。Pythonのsuper()関数を使うことで、スーパークラスを暗黙的に参照することができます。したがって、Pythonのsuperは私たちの作業をより簡単で快適にします。サブクラスからスーパークラスを参照する際に、スーパークラスの名前を明示的に書く必要はありません。以下のセクションでは、Pythonのsuper関数について説明します。

Pythonのsuper関数の例

まず、次のコードを見てみましょう。これは、Pythonの継承チュートリアルで使用したコードです。この例のコードでは、スーパークラスはPersonであり、サブクラスはStudentです。したがって、コードは以下のようになります。

class Person:
    # 変数の初期化
    name = ""
    age = 0

    # コンストラクタの定義
    def __init__(self, person_name, person_age):
        self.name = person_name
        self.age = person_age

        # クラスメソッドの定義

    def show_name(self):
        print(self.name)

    def show_age(self):
        print(self.age)


# サブクラスの定義がここから始まります
class Student(Person):
    studentId = ""

    def __init__(self, student_name, student_age, student_id):
        Person.__init__(self, student_name, student_age)
        self.studentId = student_id

    def get_id(self):
        return self.studentId  # returns the value of student id


# サブクラスの定義の終わり


# スーパークラスのオブジェクトを作成
person1 = Person("Richard", 23)
# オブジェクトのメンバーメソッドを呼び出す
person1.show_age()
# サブクラスのオブジェクトを作成
student1 = Student("Max", 22, "102")
print(student1.get_id())
student1.show_name()

上記の例では、親クラスの関数を呼び出しています:

Person.__init__(self, student_name, student_age) 

これを以下のようにPythonのsuper関数呼び出しで置き換えることができます。

super().__init__(student_name, student_age)

出力は、以下の画像に示すように、両方の場合で同じままです。

Python 3 super

上記の構文は、Python 3のsuper関数のものです。Python 2.xバージョンを使用している場合、やや異なりますので、以下の変更を行う必要があります。

class Person(object):
...
        super(Student, self).__init__(student_name, student_age)

最初の変更は、Personの基本クラスとしてobjectを持つことです。Python 2.xバージョンでは、super関数を使用する必要があります。さもないと、次のエラーが発生します。

Traceback (most recent call last):
  File "super_example.py", line 40, in <module>
    student1 = Student("Max", 22, "102")
  File "super_example.py", line 25, in __init__
    super(Student, self).__init__(student_name, student_age)
TypeError: must be type, not classobj

super関数の構文自体の2番目の変更です。Python 3のsuper関数が使いやすく、構文も見やすいことがわかります。

Pythonのスーパー関数と多段階の継承

以前に述べたように、Pythonのsuper()関数はスーパークラスを暗黙的に参照できるようにします。ただし、多段階の継承の場合、どのクラスを参照するのでしょうか?実際、Pythonのsuper()は常に直接のスーパークラスを参照します。また、Pythonのsuper()関数は__init__()関数だけでなく、スーパークラスのすべての他の関数を呼び出すこともできます。次の例で確認しましょう。

class A:
    def __init__(self):
        print('Initializing: class A')

    def sub_method(self, b):
        print('Printing from class A:', b)


class B(A):
    def __init__(self):
        print('Initializing: class B')
        super().__init__()

    def sub_method(self, b):
        print('Printing from class B:', b)
        super().sub_method(b + 1)


class C(B):
    def __init__(self):
        print('Initializing: class C')
        super().__init__()

    def sub_method(self, b):
        print('Printing from class C:', b)
        super().sub_method(b + 1)


if __name__ == '__main__':
    c = C()
    c.sub_method(1)

上記のPython 3スーパーの多段階継承の例の出力を見てみましょう。

Initializing: class C
Initializing: class B
Initializing: class A
Printing from class C: 1
Printing from class B: 2
Printing from class A: 3

したがって、出力から明らかなように、クラスCの__init__()関数が最初に呼び出され、次にクラスB、最後にクラスAが呼び出されました。同様のことがsub_method()関数を呼び出すことで起こりました。

なぜPythonのsuper関数が必要なのか

もしJava言語の以前の経験があるなら、基本クラスもそこでsuperオブジェクトとして呼び出されることを知っているはずです。したがって、このコンセプトは実際にはコーダーにとって有用です。ただし、Pythonもプログラマーがスーパークラス名を使用してそれらを参照する機能を保持しています。そして、プログラムに多段階の継承が含まれている場合、このsuper()関数は役立ちます。これがPythonのsuper関数に関するすべてです。このトピックを理解していただけたと思います。疑問がある場合はコメントボックスをご利用ください。

完全なPythonスクリプトやその他のPythonの例は、当社のGitHubリポジトリからご覧いただけます。

参考文献:公式ドキュメント

Source:
https://www.digitalocean.com/community/tutorials/python-super