Python super() 関数

Python 内置函数Python 組み込み関数


説明

super()この関数は親クラス(スーパークラス)のメソッドを呼び出すために使われます。

super()多重継承の問題を解決するためのものです。単一継承の場合はクラス名を直接使って親クラスのメソッドを呼び出しても問題ありませんが、多重継承を使用すると、メソッド解決順序(MRO)や重複呼び出し(ダイヤモンド継承)などのさまざまな問題が発生します。

MRO とはクラスのメソッド解決順序テーブルであり、実際には親クラスのメソッドを継承するときの順序テーブルです。

構文

以下は super() メソッドの構文です:

super(type[, object-or-type])

パラメータ

  • type -- クラス。
  • object-or-type -- クラス。通常は self です。

Python3.x と Python2.x の違いの1つは、Python 3 では直接使用できることです。super().xxx代わりに使用できますsuper(Class, self).xxx :

Python3.x の例:

class A: def add(self, x): y = x+1 print(y) class B(A): def add(self, x): super().add(x) b = B() b.add(2) # 3

Python2.x の例:

#!/usr/bin/python # -*- coding: UTF-8 -*- class A(object): # Python2.x では object を継承することを忘れないでください def add(self, x): y = x+1 print(y) class B(A): def add(self, x): super(B, self).add(x) b = B() b.add(2) # 3

戻り値

なし。


例

以下は super 関数を使用した例です:

例

#!/usr/bin/python # -*- coding: UTF-8 -*- class FooParent(object): def __init__(self): self.parent = 'I\'m the parent.' print ('Parent') def bar(self,message): print ("%s from Parent" % message) class FooChild(FooParent): def __init__(self): # super(FooChild,self) は最初に FooChild の親クラス(つまりクラス FooParent)を見つけ、次に FooChild クラスのオブジェクトを FooParent クラスのオブジェクトに変換します super(FooChild,self).__init__() print ('Child') def bar(self,message): super(FooChild, self).bar(message) print ('Child bar fuction') print (self.parent) if __name__ == '__main__': fooChild = FooChild() fooChild.bar('HelloWorld')

実行結果:

Parent
Child
HelloWorld from Parent
Child bar fuction
I'm the parent.

Python 内置函数Python 組み込み関数

その他の拡張