Python スーパー()

Python では、親クラスまたはスーパークラスを参照するために super() 関数が使用されます。これにより、スーパークラスで定義されたメソッドをサブクラスから呼び出すことができ、親クラスから継承した機能を拡張およびカスタマイズできるようになります。

Python の super() の構文

構文: 素晴らしい()

戻る : 親のクラスを表すプロキシ オブジェクトを返します。

Python の super() 関数の例

与えられた例では、 エンプ クラスには __熱い__ を初期化するメソッド ID 、 そして 名前 そして 追加します 属性。の フリーランス クラスはから継承します エンプ クラスを作成し、という追加の属性を追加します。 メール。親クラスの __init__ メソッド super() を呼び出して、継承された属性を初期化します。

Python3




class> Emp():> > def> __init__(> self> ,> id> , name, Add):> > self> .> id> => id> > self> .name> => name> > self> .Add> => Add> # Class freelancer inherits EMP> class> Freelance(Emp):> > def> __init__(> self> ,> id> , name, Add, Emails):> > super> ().__init__(> id> , name, Add)> > self> .Emails> => Emails> Emp_1> => Freelance(> 103> ,> 'Suraj kr gupta'> ,> 'Noida'> ,> 'KKK@gmails'> )> print> (> 'The ID is:'> , Emp_1.> id> )> print> (> 'The Name is:'> , Emp_1.name)> print> (> 'The Address is:'> , Emp_1.Add)> print> (> 'The Emails is:'> , Emp_1.Emails)>

出力:

The ID is: 103 The Name is: Suraj kr gupta The Address is: Noida The Emails is: KKK@gmails 

super () メソッドは何に使用されますか?

親クラスのメソッドは、Python で super() 関数を使用して呼び出すことができます。それは典型的な習慣です オブジェクト指向プログラミング スーパークラスのメソッドを呼び出し、メソッドのオーバーライドと継承を有効にします。現在のクラスがこれらのメソッドを独自の実装に置き換えた場合でも、super() を呼び出すと、親クラスのメソッドにアクセスして使用できるようになります。こうすることで、親クラスの動作を拡張および変更しながら、そこから利益を得ることもできます。

スーパーファンクションのメリット

  • そのメソッドにアクセスするために親クラス名を覚えたり指定したりする必要はありません。この関数は、単一継承と複数継承の両方で使用できます。
  • これにより、関数全体を書き直す必要がないため、モジュール性 (変更の分離) とコードの再利用性が実装されます。
  • Python は他の言語とは異なり動的言語であるため、Python のスーパー関数は動的に呼び出されます。

Python スーパーなしで継承はどのように機能しますか?

この例では、Emp クラスの __init__ メソッドに問題があります。 Emp クラスは Person クラスから継承されていますが、その __init__ メソッドでは、name 属性と id 属性を初期化するために親クラスの __init__ メソッドを呼び出していません。

Python3




# code> class> Person:> > # Constructor> > def> __init__(> self> , name,> id> ):> > self> .name> => name> > self> .> id> => id> > # To check if this person is an employee> > def> Display(> self> ):> > print> (> self> .name,> self> .> id> )> > class> Emp(Person):> > > def> __init__(> self> , name,> id> ):> > self> .name_> => name> > def> Print> (> self> ):> > print> (> 'Emp class called'> )> Emp_details> => Emp(> 'Mayank'> ,> 103> )> # calling parent class function> Emp_details.name_, Emp_details.name>

出力:

--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) in 24 25 # calling parent class function --->26 Emp_details.name_、Emp_details.name 属性エラー: 'Emp' オブジェクトには属性 'name' がありません 

Python の Super を使用して上記の問題を修正する

提供されたコードでは、Emp クラスは Person クラスから正しく継承されており、Emp クラスの __init__ メソッドは、Python の super() を使用して親クラスの __init__ メソッドを適切に呼び出しています。

Python3




# code> # A Python program to demonstrate inheritance> class> Person:> > # Constructor> > def> __init__(> self> , name,> id> ):> > self> .name> => name> > self> .> id> => id> > # To check if this person is an employee> > def> Display(> self> ):> > print> (> self> .name,> self> .> id> )> > class> Emp(Person):> > > def> __init__(> self> , name,> id> ):> > self> .name_> => name> > super> ().__init__(name,> id> )> > def> Print> (> self> ):> > print> (> 'Emp class called'> )> Emp_details> => Emp(> 'Mayank'> ,> 103> )> # calling parent class function> print> (Emp_details.name_, Emp_details.name)>

出力:

Mayank Mayank 

Python super() と __init__() メソッドを理解する

Python には __init__ という予約メソッドがあります。オブジェクト指向プログラミングでは、コンストラクターと呼ばれます。このメソッドが呼び出されると、クラスはクラスの属性を初期化できるようになります。継承されたサブクラスでは、super() 関数を使用して親クラスを参照できます。スーパー関数は、その子クラスのすべてのメソッドへのアクセスを許可するスーパークラスの一時オブジェクトを返します。

注記: 詳細については、以下を参照してください。 Python の継承

単一継承によるスーパー関数

動物の例を見てみましょう。犬、猫、牛も動物の一部です。また、次のような共通の特徴もあります。

  • 彼らは哺乳類です。
  • 尻尾と 4 本の足があります。
  • 彼らは家畜です。

したがって、犬、猫、馬のクラスは動物クラスのサブクラスです。多くのサブクラスが単一親クラスから継承されるため、これは単一継承の例です。

Python3




# Python program to demonstrate> # super function> class> Animals:> > # Initializing constructor> > def> __init__(> self> ):> > self> .legs> => 4> > self> .domestic> => True> > self> .tail> => True> > self> .mammals> => True> > def> isMammal(> self> ):> > if> self> .mammals:> > print> (> 'It is a mammal.'> )> > def> isDomestic(> self> ):> > if> self> .domestic:> > print> (> 'It is a domestic animal.'> )> class> Dogs(Animals):> > def> __init__(> self> ):> > super> ().__init__()> > def> isMammal(> self> ):> > super> ().isMammal()> class> Horses(Animals):> > def> __init__(> self> ):> > super> ().__init__()> > def> hasTailandLegs(> self> ):> > if> self> .tail> and> self> .legs> => => 4> :> > print> (> 'Has legs and tail'> )> # Driver code> Tom> => Dogs()> Tom.isMammal()> Bruno> => Horses()> Bruno.hasTailandLegs()>

出力:

It is a mammal. Has legs and tail 

複数の継承を持つスーパー

もう一つ取りましょう スーパー関数の例 , クラスがあるとします。 飛べる そして 泳げる 哺乳類クラスから継承され、これらのクラスは動物クラスによって継承されます。したがって、動物クラスは複数の基本クラスから継承します。の使い方を見てみましょう パイソン 引数付きのスーパー この場合。

Python3




class> Mammal():> > def> __init__(> self> , name):> > print> (name,> 'Is a mammal'> )> class> canFly(Mammal):> > def> __init__(> self> , canFly_name):> > print> (canFly_name,> 'cannot fly'> )> > # Calling Parent class> > # Constructor> > super> ().__init__(canFly_name)> class> canSwim(Mammal):> > def> __init__(> self> , canSwim_name):> > print> (canSwim_name,> 'cannot swim'> )> > super> ().__init__(canSwim_name)> class> Animal(canFly, canSwim):> > def> __init__(> self> , name):> > super> ().__init__(name)> # Driver Code> Carol> => Animal(> 'Dog'> )>

出力:

Animal クラスは、2 つの親クラス、canFly と canSwim から継承します。したがって、サブクラス インスタンス Carol は両方の親クラス コンストラクターにアクセスできます。

Dog cannot fly Dog cannot swim Dog Is a mammal 

マルチレベル継承を備えたスーパー

もう一つ取りましょう スーパー関数の例 、クラス can swim が哺乳類クラスの canFly、canFly によって継承されているとします。したがって、哺乳類クラスはマルチレベル継承から継承します。の使い方を見てみましょう パイソン 引数付きのスーパー この場合。

Python3




class> Mammal():> > def> __init__(> self> , name):> > print> (name,> 'Is a mammal'> )> class> canFly(Mammal):> > def> __init__(> self> , canFly_name):> > print> (canFly_name,> 'cannot fly'> )> > # Calling Parent class> > # Constructor> > super> ().__init__(canFly_name)> class> canSwim(canFly):> > def> __init__(> self> , canSwim_name):> > print> (canSwim_name,> 'cannot swim'> )> > super> ().__init__(canSwim_name)> class> Animal(canSwim):> > def> __init__(> self> , name):> > # Calling the constructor> > # of both the parent> > # class in the order of> > # their inheritance> > super> ().__init__(name)> # Driver Code> Carol> => Animal(> 'Dog'> )>

出力:

Dog cannot swim Dog cannot fly Dog Is a mammal 

Python の多重継承と MRO

指定された例では、クラス C はクラス A および B を継承し、age() メソッドをオーバーライドします。ただし、クラス C の age() メソッドでは、super(C, self).age() 行が MRO 内の次のクラスから age() メソッドを呼び出します。この場合、クラス A は MRO 内でクラス B の前に現れるため、クラス A から age() メソッドを呼び出します。

Python3




class> A:> > def> age(> self> ):> > print> (> 'Age is 21'> )> class> B:> > def> age(> self> ):> > print> (> 'Age is 23'> )> class> C(A, B):> > def> age(> self> ):> > super> (C,> self> ).age()> > c> => C()> print> (C.__mro__)> print> (C.mro())>

出力:

(, , , ) [, , , ]