の中核となる概念の 1 つ オブジェクト指向プログラミング (OOP) 言語は継承です。これは、別のクラスからクラスを派生することによって、プロパティとメソッドのセットを共有するクラスの階層を作成できるメカニズムです。継承とは、あるクラスが別のクラスからプロパティを派生または継承する機能です。
継承の利点は次のとおりです。
継承を使用すると、クラス (基本クラス) のプロパティを別のクラス (派生クラス) に継承できます。 Python での継承の利点は次のとおりです。
- 現実世界の人間関係をよく表しています。
- それは、 再利用性 コードの。同じコードを何度も書く必要はありません。また、クラスを変更せずに、クラスに機能を追加することもできます。
- これは本質的に推移的です。つまり、クラス B が別のクラス A から継承する場合、B のすべてのサブクラスは自動的にクラス A から継承します。
- 継承は、シンプルでわかりやすいモデル構造を提供します。
- 相続による開発費や保守費が少なくなります。
Python の継承構文
Python での単純な継承の構文は次のとおりです。
Class BaseClass: {Body} Class DerivedClass(BaseClass): {Body}> 親クラスの作成
親クラスは、そのプロパティが子クラスに継承されるクラスです。という親クラスを作成しましょう 人 を持っている 画面 個人の情報を表示する方法。
Python3
# A Python program to demonstrate inheritance> class> Person(>object>):> > ># 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>)> # Driver code> emp>=> Person(>'Satyam'>,>102>)># An Object of Person> emp.Display()> |
>
>
出力:
Satyam 102>
子クラスの作成
子クラスは、親クラスからプロパティを駆動するクラスです。ここ エンプ のプロパティを継承する別のクラスです。 人 クラス(基本クラス)。
Python3
Java リスト
class> Emp(Person):> > >def> Print>(>self>):> >print>(>'Emp class called'>)> > Emp_details>=> Emp(>'Mayank'>,>103>)> # calling parent class function> Emp_details.Display()> # Calling child class function> Emp_details.>Print>()> |
>
>
出力:
Mayank 103 Emp class called>
Python での継承の例
子クラスが親クラスのプロパティを継承する単純な Python 継承の例を見てみましょう。この例では、「Person」が親クラスで、「Employee」がその子クラスです。
Python3
# A Python program to demonstrate inheritance> # Base or Super class. Note object in bracket.> # (Generally, object is made ancestor of all classes)> # In Python 3.x 'class Person' is> # equivalent to 'class Person(object)'> class> Person(>object>):> ># Constructor> >def> __init__(>self>, name):> >self>.name>=> name> ># To get name> >def> getName(>self>):> >return> self>.name> ># To check if this person is an employee> >def> isEmployee(>self>):> >return> False> # Inherited or Subclass (Note Person in bracket)> class> Employee(Person):> ># Here we return true> >def> isEmployee(>self>):> >return> True> # Driver code> emp>=> Person(>'Geek1'>)># An Object of Person> print>(emp.getName(), emp.isEmployee())> emp>=> Employee(>'Geek2'>)># An Object of Employee> print>(emp.getName(), emp.isEmployee())> |
>
>
出力:
Geek1 False Geek2 True>
Pythonのオブジェクトクラスとは何ですか?
以下のような Javaオブジェクトクラス , Python (バージョン 3.x 以降) では、オブジェクトはすべてのクラスのルートです。
- Python 3.x では、クラス Test(object) とクラス Test は同じです。
- Python 2.x では、クラス Test(object) はオブジェクトを親とするクラス (新しいスタイルのクラスと呼ばれる) を作成し、クラス Test は古いスタイルのクラス (オブジェクトとなる親を持たない) を作成します。
サブクラス化 (親クラスのコンストラクターの呼び出し)
子クラスは、どのクラスがその親クラスであるかを識別する必要があります。これは、子クラスの定義で親クラス名を指定することで実行できます。
例: クラスのサブクラス名 (スーパークラス名)
この例では、 「あ」 は、クラス Person に対して作成されたインスタンスです。参照されたクラスの __init__() を呼び出します。クラス Person の宣言に「object」が記述されていることがわかります。 Python では、すべてのクラスは「オブジェクト」と呼ばれる組み込みの基本クラスを継承します。コンストラクター、つまりクラスの「__init__」関数は、オブジェクト変数またはクラスのインスタンスを作成するときに呼び出されます。
__init__() 内で定義された変数は、インスタンス変数またはオブジェクトと呼ばれます。したがって、「name」と「idnumber」はクラス person のオブジェクトです。同様に、「salary」と「post」はクラス Employee のオブジェクトです。クラス Employee はクラス Person から継承しているため、「name」と「idnumber」もクラス Employee のオブジェクトです。
Python3
# Python code to demonstrate how parent constructors> # are called.> # parent class> class> Person(>object>):> ># __init__ is known as the constructor> >def> __init__(>self>, name, idnumber):> >self>.name>=> name> >self>.idnumber>=> idnumber> >def> display(>self>):> >print>(>self>.name)> >print>(>self>.idnumber)> # child class> class> Employee(Person):> >def> __init__(>self>, name, idnumber, salary, post):> >self>.salary>=> salary> >self>.post>=> post> ># invoking the __init__ of the parent class> >Person.__init__(>self>, name, idnumber)> # creation of an object variable or an instance> a>=> Employee(>'Rahul'>,>886012>,>200000>,>'Intern'>)> # calling a function of the class Person using its instance> a.display()> |
>
>
出力:
リストから配列Javaへ
Rahul 886012>
親の __init__() を呼び出すのを忘れた場合のエラーを示す Python プログラム
親クラスの __init__() を呼び出すのを忘れた場合、そのインスタンス変数は子クラスで使用できなくなります。次のコードでも、同じ理由でエラーが発生します。
Python3
class> A:> >def> __init__(>self>, n>=>'Rahul'>):> >self>.name>=> n> class> B(A):> >def> __init__(>self>, roll):> >self>.roll>=> roll> object> => B(>23>)> print>(>object>.name)> |
>
>
出力:
Traceback (most recent call last): File '/home/de4570cca20263ac2c4149f435dba22c.py', line 12, in print (object.name) AttributeError: 'B' object has no attribute 'name'>
super() 関数
の スーパー()関数 は、親クラスを表すオブジェクトを返す組み込み関数です。これにより、子クラス内の親クラスのメソッドと属性にアクセスできるようになります。
例: 単純な Python 継承を使用した super() 関数
この例では、子クラスのオブジェクト「obj」を作成しました。子クラス「Student」のコンストラクターを呼び出すと、オブジェクトの作成時に渡された値にデータ メンバーが初期化されます。次に、super() 関数を使用して、親クラスのコンストラクターを呼び出しました。
Python3
# parent class> class> Person():> >def> __init__(>self>, name, age):> >self>.name>=> name> >self>.age>=> age> >def> display(>self>):> >print>(>self>.name,>self>.age)> # child class> class> Student(Person):> >def> __init__(>self>, name, age):> >self>.sName>=> name> >self>.sAge>=> age> ># inheriting the properties of parent class> >super>().__init__(>'Rahul'>, age)> >def> displayInfo(>self>):> >print>(>self>.sName,>self>.sAge)> obj>=> Student(>'Mayank'>,>23>)> obj.display()> obj.displayInfo()> |
>
>
出力:
Rahul 23 Mayank 23>
プロパティの追加
継承が提供する機能の 1 つは、親クラスのプロパティを継承することと、独自の新しいプロパティを子クラスに追加することです。これを例で見てみましょう。
Python3
# parent class> class> Person():> >def> __init__(>self>, name, age):> >self>.name>=> name> >self>.age>=> age> >def> display(>self>):> >print>(>self>.name,>self>.age)> # child class> class> Student(Person):> >def> __init__(>self>, name, age, dob):> >self>.sName>=> name> >self>.sAge>=> age> >self>.dob>=> dob> ># inheriting the properties of parent class> >super>().__init__(>'Rahul'>, age)> >def> displayInfo(>self>):> >print>(>self>.sName,>self>.sAge,>self>.dob)> obj>=> Student(>'Mayank'>,>23>,>'16-03-2000'>)> obj.display()> obj.displayInfo()> |
>
>
出力:
ここでは、子クラスに新しいプロパティ、つまり生年月日 (dob) を追加したことがわかります。
Rahul 23 Mayank 23 16-03-2000>
さまざまな種類の Python 継承
Python には 5 つの異なるタイプの継承があります。それらは次のとおりです。
- 単一継承 : 子クラスが 1 つの親クラスのみから継承する場合、それを単一継承と呼びます。上で例を見ました。多重継承 : 子クラスが複数の親クラスから継承することを多重継承と呼びます。
Java とは異なり、Python は複数の継承を示します。
Python3
Javaはそうではありません
# Python example to show the working of multiple> # inheritance> class> Base1(>object>):> >def> __init__(>self>):> >self>.str1>=> 'Geek1'> >print>(>'Base1'>)> class> Base2(>object>):> >def> __init__(>self>):> >self>.str2>=> 'Geek2'> >print>(>'Base2'>)> class> Derived(Base1, Base2):> >def> __init__(>self>):> ># Calling constructors of Base1> ># and Base2 classes> >Base1.__init__(>self>)> >Base2.__init__(>self>)> >print>(>'Derived'>)> >def> printStrs(>self>):> >print>(>self>.str1,>self>.str2)> ob>=> Derived()> ob.printStrs()> |
>
>
出力:
Base1 Base2 Derived Geek1 Geek2>
- 多段階継承:子と孫の関係がある場合。これは、子クラスがその親クラスを継承し、さらにその親クラスがその親クラスを継承することを意味します。
Python3
# A Python program to demonstrate inheritance> # Base or Super class. Note object in bracket.> # (Generally, object is made ancestor of all classes)> # In Python 3.x 'class Person' is> # equivalent to 'class Person(object)'> class> Base(>object>):> ># Constructor> >def> __init__(>self>, name):> >self>.name>=> name> ># To get name> >def> getName(>self>):> >return> self>.name> # Inherited or Sub class (Note Person in bracket)> class> Child(Base):> ># Constructor> >def> __init__(>self>, name, age):> >Base.__init__(>self>, name)> >self>.age>=> age> ># To get name> >def> getAge(>self>):> >return> self>.age> # Inherited or Sub class (Note Person in bracket)> class> GrandChild(Child):> ># Constructor> >def> __init__(>self>, name, age, address):> >Child.__init__(>self>, name, age)> >self>.address>=> address> ># To get address> >def> getAddress(>self>):> >return> self>.address> # Driver code> g>=> GrandChild(>'Geek1'>,>23>,>'Noida'>)> print>(g.getName(), g.getAge(), g.getAddress())> |
>
>
出力:
Geek1 23 Noida>
- 階層的な継承 1 つのベースから複数の派生クラスを作成できます。ハイブリッド継承 : この形式は、複数の形式の継承を組み合わせたものです。基本的に、それは複数のタイプの継承の混合です。
詳細については、次の記事をご覧ください。 Python の継承の種類
親クラスのプライベートメンバー
親クラスのインスタンス変数が子クラスに継承されることを常に望んでいるわけではありません。つまり、親クラスのインスタンス変数の一部をプライベートにし、子クラスでは使用できないようにすることができます。
Python の継承では、名前の前に 2 つのアンダースコアを追加することで、インスタンス変数をプライベートにすることができます。例えば:
Python3
# Python program to demonstrate private members> # of the parent class> class> C(>object>):> >def> __init__(>self>):> >self>.c>=> 21> ># d is private instance variable> >self>.__d>=> 42> class> D(C):> >def> __init__(>self>):> >self>.e>=> 84> >C.__init__(>self>)> object1>=> D()> # produces an error as d is private instance variable> print>(object1.c)> print>(object1.__d)> |
>
>
出力:
ここでは、変数「c」を出力しようとすると、その値 21 がコンソールに出力されることがわかります。一方、「d」を出力しようとすると、エラーが発生しました。これは、変数「d」がアンダースコアを使用して非公開になっているためです。子クラス「D」では使用できないため、エラーが発生します。
21 File '/home/993bb61c3e76cda5bb67bd9ea05956a1.py', line 16, in print (object1.d) AttributeError: type object 'D' has no attribute 'd'>