ウェブサイト検索

Pythonのsuper() - Python 3のsuper()


Pythonのsuper()関数は、親クラスを明示的に参照することを可能にします。これは、スーパークラスの関数を呼び出したい場合の継承において便利です。

Pythonのsuper

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

Pythonのスーパーファンクションの例

最初に、私たちのPython継承チュートリアルで使用した以下のコードを見てください。その例のコードでは、スーパークラスはPersonで、サブクラスはStudentでした。コードは以下のように示されています。

class Person:
    # initializing the variables
    name = ""
    age = 0

    # defining constructor
    def __init__(self, person_name, person_age):
        self.name = person_name
        self.age = person_age

        # defining class methods

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

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


definition of subclass starts here
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


end of subclass definition


Create an object of the superclass
person1 = Person("Richard", 23)
call member methods of the objects
person1.show_age()
Create an object of the subclass
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 スーパ

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

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

最初の変更は、objectをPersonの基底クラスとして持つことです。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

スーパー関数自体の構文の2番目の変更です。Python 3 のスーパー関数は使用がずっと簡単で、構文も見た目がきれいです。

マルチレベル継承を使用したPythonのsuper関数

以前述べたように、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リポジトリからチェックできます。

参照:公式ドキュメント

関連記事: